471,330 Members | 1,053 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,330 software developers and data experts.

finding the median item in a list

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
2 16465
bartonc
6,596 Expert 4TB
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
6,596 Expert 4TB
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.

Similar topics

8 posts views Thread by nick.vitone | last post: by
2 posts views Thread by ElkGroveR | last post: by
7 posts views Thread by Bhadan | last post: by
3 posts views Thread by mehwishobaid | last post: by
7 posts views Thread by tomshorts07 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.