Numeric elements of a mixed list

Thread Solved

Join Date: Mar 2007
Posts: 1,521
Reputation: Lardmeister is an unknown quantity at this point 
Solved Threads: 22
Lardmeister's Avatar
Lardmeister Lardmeister is offline Offline
Posting Virtuoso

Numeric elements of a mixed list

 
0
  #1
Aug 11th, 2007
Right now I have a mixed list of different types of elements:
  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?
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,003
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 927
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Numeric elements of a mixed list

 
0
  #2
Aug 11th, 2007
The easiest way is to extablish a temporary list of numeric values ...
  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 ...
  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
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Mar 2007
Posts: 1,521
Reputation: Lardmeister is an unknown quantity at this point 
Solved Threads: 22
Lardmeister's Avatar
Lardmeister Lardmeister is offline Offline
Posting Virtuoso

Re: Numeric elements of a mixed list

 
0
  #3
Aug 20th, 2007
Thank you Vega!
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC