By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,842 Members | 2,198 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,842 IT Pros & Developers. It's quick & easy.

finding the median item in a list

P: 1
lets say i have this list:
numbers = ['4', '3.2', '3.1', '3.15', '20', '3', '4', '17', '8']

and i want my script to tell me that the highest number in the list is '20'

how can i do that?
what if you wanted to find a number in the middle of that list: how would you go about that?
Sep 8 '07 #1
Share this Question
Share on Google+
2 Replies


bartonc
Expert 5K+
P: 6,596
what if you wanted to find a number in the middle of that list: how would you go about that?
Here's one way:
Expand|Select|Wrap|Line Numbers
  1. >>> numbers = ('4', '3.2', '3.1', '3.15', '20', '3', '4', '17', '8')
  2. >>> floatList = sorted([float(x) for x in numbers])
  3. >>> floatList
  4. [3.0, 3.1000000000000001, 3.1499999999999999, 3.2000000000000002, 4.0, 4.0, 8.0, 17.0, 20.0]
  5. >>> average = sum(floatList)//len(floatList)
  6. >>> average
  7. 7.0
  8. >>> for i, item in enumerate(floatList):
  9. ...     if item > average:
  10. ...         print "%f is between %f and %f" %(average, item, floatList[i + 1])
  11. ...         break 
  12. 7.000000 is between 8.000000 and 17.000000
  13. >>> 
Sep 8 '07 #2

bartonc
Expert 5K+
P: 6,596
what if you wanted to find a number in the middle of that list: how would you go about that?
Or, if all you want is the number closest in position to the middle, then it's:
Expand|Select|Wrap|Line Numbers
  1. >>> print floatList[len(floatList)/2]
  2. 4.0
  3. >>> 
Sep 8 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.