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?
Lardmeister
Posting Virtuoso
1,749 posts since Mar 2007
Reputation Points: 407
Solved Threads: 43
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
vegaseat
DaniWeb's Hypocrite
5,976 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,416
Lardmeister
Posting Virtuoso
1,749 posts since Mar 2007
Reputation Points: 407
Solved Threads: 43