943,936 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 1591
  • Python RSS
Aug 11th, 2007
0

Numeric elements of a mixed list

Expand Post »
Right now I have a mixed list of different types of elements:
python Syntax (Toggle Plain Text)
  1. mixed_list = [1, 0.5, 0, 3, 'a', 'z']
  2.  
  3. print max(mixed_list) # shows z, but would like it to be 3
How can I find the maximum numeric element of the list?
Similar Threads
Reputation Points: 407
Solved Threads: 36
Posting Virtuoso
Lardmeister is offline Offline
1,701 posts
since Mar 2007
Aug 11th, 2007
0

Re: Numeric elements of a mixed list

The easiest way is to extablish a temporary list of numeric values ...
python Syntax (Toggle Plain Text)
  1. mixed_list = [1, 0.5, 0, 3, 'a', 'z']
  2.  
  3. print max(mixed_list) # shows z, but would like it to be 3
  4.  
  5. number_list = []
  6. for x in mixed_list:
  7. if type(x) in (int, float):
  8. number_list.append(x)
  9.  
  10. print number_list
  11. print max(number_list) # 3
You can shorten this with a list comprehension ...
python Syntax (Toggle Plain Text)
  1. mixed_list = [1, 0.5, 0, 3, 'a', 'z']
  2.  
  3. print max([x for x in mixed_list if type(x) in (int, float)]) # 3
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Aug 20th, 2007
0

Re: Numeric elements of a mixed list

Thank you Vega!
Reputation Points: 407
Solved Threads: 36
Posting Virtuoso
Lardmeister is offline Offline
1,701 posts
since Mar 2007

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: Animated Images
Next Thread in Python Forum Timeline: play sound help





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC