0

I have to sort this python list :

55.115783, 62.380159, 68.738354, 66.014074, 72.073756, 69.036055, 71.594129, 77.551457, 75.922748, 81.613726, 89.083050, 94.257211, 96.328673 ,102.489464, 111.449678, 118.870730

if I try to use list.sort() I obtain this :

102.489464, 111.449678, 118.870730, 55.115783, 62.380159, 66.014074, 68.738354, 69.036055, 71.594129, 72.073756, 75.922748, 77.551457, 81.613726, 89.083050, 94.257211, 96.328673

I really don't know why !! may somebody help me about !!

Drudox lebowsky
  • 1,020
  • 7
  • 21
  • 5
    it would help if you gave us the actual "list" you were working with, however i can already see the issue. you have a list of strings! And they were being sorted lexically. Convert to list of floats before sorting – Paritosh Singh Jul 21 '19 at 11:31

1 Answers1

2

Your values are being sorted as strings - 102 vs 5 will be sorted based on the first 1 in the string (and will thus be sorted in front of 5) - and not the numeric value.

The easiest way to solve this is to use the float function together with key in the call to sorted:

>>> a = ['123', '6']
>>> sorted(a)
['123', '6']
>>> sorted(a, key=float)
['6', '123']

The key parameter takes a function that will be applied to each entry before determining the sort value, and this will give you a numeric value to sort by instead.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • This is true if the required output is a list of strings. If the output required is a list of floats, a possible solution is `sorted(map(float, a))` – DeepSpace Jul 21 '19 at 11:34
  • Yup. I'd suggest appliing it before sorting to be clearer about the intent in that case, since it'll explicitly state "we want to convert this list to a float list". This will require the user to be aware of possible shortcoming about a conversion to float, though - such as possibly not getting the same representation back as the original string represents. – MatsLindh Jul 21 '19 at 11:37