Reputation: 1297
I have the following list that I'd like to sort:
['104.900209904', '238.501860857', '9.59893298149', '362.470027924', '419.737339973']
I used the "sorted" function to do it:
Block1_Video1 = sorted(Block1_Video1)
However, this is what I get:
['104.900209904', '238.501860857', '362.470027924', '419.737339973', '9.59893298149']
Whereas this is what I want (a list sorted numerically, taking decimal points into account):
[''9.59893298149', 104.900209904', '238.501860857', '362.470027924', '419.737339973']
How can I accomplish this?
Upvotes: 3
Views: 9081
Reputation: 49260
The sorting needs to be based on the float values of the corresponding strings in the list.
Block1_Video1 = ['104.900209904', '238.501860857', '9.59893298149', '362.470027924', '419.737339973']
sorted(Block1_Video1,key=lambda x:float(x))
Or simply use
sorted(Block1_Video1, key=float)
Upvotes: 10
Reputation: 42758
You have to convert your strings in numbers first, this is possible with the key-Argument of the sorted
function:
Block1_Video1 = sorted(Block1_Video1, key=float)
or as you assign the new list to the same variable, you can also sort in-place:
Block1_Video1.sort(key=float)
Upvotes: 1