DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Python (http://www.daniweb.com/forums/forum114.html)
-   -   Numeric elements of a mixed list (http://www.daniweb.com/forums/thread85986.html)

Lardmeister Aug 11th, 2007 4:08 pm
Numeric elements of a mixed list
 
Right now I have a mixed list of different types of elements:
mixed_list = [1, 0.5, 0, 3, 'a', 'z']

print max(mixed_list)  # shows z, but would like it to be 3
How can I find the maximum numeric element of the list?

vegaseat Aug 11th, 2007 6:25 pm
Re: Numeric elements of a mixed list
 
The easiest way is to extablish a temporary list of numeric values ...
mixed_list = [1, 0.5, 0, 3, 'a', 'z']

print max(mixed_list)  # shows z, but would like it to be 3
 
number_list = []
for x in mixed_list:
    if type(x) in (int, float):
        number_list.append(x)
 
print number_list
print max(number_list)  # 3
You can shorten this with a list comprehension ...
mixed_list = [1, 0.5, 0, 3, 'a', 'z']
 
print max([x for x in mixed_list if type(x) in (int, float)])  # 3

Lardmeister Aug 20th, 2007 1:39 am
Re: Numeric elements of a mixed list
 
Thank you Vega!


All times are GMT -4. The time now is 12:55 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC