pythonlistsortingfloating-point

sorting list of decimals in python


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?


Solution

  • 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)