2

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?

1
  • Your list is a list of strings, not numbers. It is sorting them alphabetically, not numerically. That is why it is acting funny. I'd post the answer but I see someone already bet me to it, I just wanted to elaborate on that. Commented Aug 17, 2016 at 20:38

3 Answers 3

10

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

-1

def sort_decimals(numbers: List[float]) -> List[float]: return sorted(numbers) print(sort_decimals(['104.900209904', '238.501860857', '9.59893298149', '362.470027924', '419.737339973']))

1 Comment

Don’t add code only answers. Explain what your code does why it works and how it helps to solve the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.