472,988 Members | 2,407 Online

# 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 16550
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