Reputation: 109
I have a list of numbers that I need to sort to get different calculations done and I noticed that the .sort() function is sorting 2 digit numbers (10-99) and 3 digit numbers (100-999) separately in the list so I end up getting the wrong values for min(), max() and the median, any idea why this is happening?
before sorting:
[' 75.0', ' 82.43', ' 112.11', ' 89.93', ' 103.19', ' 80.6', ' 113.44', ' 105.44', ' 95.54', ' 121.98', ' 114.25', ' 109.84', ' 90.48', ' 105.84', ' 82.89', ' 113.64', ' 102.73', ' 104.57', ' 100.83', ' 75.59', ' 79.86', ' 91.11', ' 94.75', ' 109.89', ' 117.39', ' 74.71', ' 71.04', ' 92.97', ' 88.87', ' 92.95', ' 86.67', ' 101.46', ' 92.4', ' 85.2', ' 107.19', ' 117.81', ' 90.95', ' 82.02', ' 87.31', ' 106.53', ' 86.28', ' 106.62', ' 107.57', ' 89.38', ' 105.88', ' 74.45', ' 90.03', ' 107.96', ' 77.42', ' 98.9', ' 109.81', ' 102.51', ' 116.71', ' 82.92', ' 81.78', ' 74.42', ' 76.27', ' 73.84', ' 75.55', ' 102.29', ' 108.1', ' 98.84', ' 101.48', ' 77.75', ' 98.57', ' 70.31', ' 78.28', ' 80.18']
and after sorting
[' 100.83', ' 101.46', ' 101.48', ' 102.29', ' 102.51', ' 102.73', ' 103.19', ' 104.57', ' 105.44', ' 105.84', ' 105.88', ' 106.53', ' 106.62', ' 107.19', ' 107.57', ' 107.96', ' 108.1', ' 109.81', ' 109.84', ' 109.89', ' 112.11', ' 113.44', ' 113.64', ' 114.25', ' 116.71', ' 117.39', ' 117.81', ' 121.98', ' 70.31', ' 71.04', ' 73.84', ' 74.42', ' 74.45', ' 74.71', ' 75.0', ' 75.55', ' 75.59', ' 76.27', ' 77.42', ' 77.75', ' 78.28', ' 79.86', ' 80.18', ' 80.6', ' 81.78', ' 82.02', ' 82.43', ' 82.89', ' 82.92', ' 85.2', ' 86.28', ' 86.67', ' 87.31', ' 88.87', ' 89.38', ' 89.93', ' 90.03', ' 90.48', ' 90.95', ' 91.11', ' 92.4', ' 92.95', ' 92.97', ' 94.75', ' 95.54', ' 98.57', ' 98.84', ' 98.9']
Upvotes: 1
Views: 112
Reputation: 90919
Because you have a list of strings , so it is getting sorted in lexicographical order , If you are sure the list only have float values (in strings) , the use the keys argument to convert those strings to float while sorting. Example -
l.sort(float)
If you want to convert the complete list to float (since you say you want to take mean / median , etc later ) , then use -
l = list(map(float, l))
For Python 2.x , the list(..) is not needed as map() returns a list .
And if you are converting the complete list to float , then you do not need the above sort() method with keys argument , normal .sort() should work.
Upvotes: 7