44

I am trying to sort list of strings containing numbers:

a = ["1099.0","9049.0"]
a.sort()
a
['1099.0', '9049.0']

b = ["949.0","1099.0"]
b.sort()

b
['1099.0', '949.0']

a
['1099.0', '9049.0']

But list b is sorting and not list a.

5

4 Answers 4

94

You want to sort based on the float values (not string values), so try:

>>> b = ["949.0","1099.0"]
>>> b.sort(key=float)
>>> b
['949.0', '1099.0']
Sign up to request clarification or add additional context in comments.

Comments

21

Use a lambda inside 'sort' to convert them to float and then sort properly:

a = sorted(a, key=lambda x: float(x))

So you will maintain them as strings, but sorted by value and not lexicographically.

2 Comments

@Keyser My point is you don't need a lambda, you can just use key=float.
to make my answer cool? actually, I forgot about the key functions. @Keyser using sort(key=float) achieves the same
13

In case anybody is dealing with numbers and extensions such as 0.png, 1.png, 10.png, 2.png... We need to retrieve and sort the characters before the extension since this extension does not let us to convert the names to floats:

myList = sorted(myList, key=lambda x: int(x[:-4]))

PD: After many years I have edited this answer changing float to int because I guess it is more efficient and more precise. It is a rare case to need floats for this purpose and it might bring errors.

2 Comments

remember to update the list too like myList = sorted(myList, key=lambda x: float(x[:-4]))
If you want to update the list, you can also use myList.sort(key=...) instead of sorted(myList, key=...),
3

Convert them to int or float or even decimal (since it has trailing numbers)

>>> b = [float(x) for x in b]
>>> b.sort()
>>> b
[949.0, 1099.0]

1 Comment

This would mean changing the types of the elements in b, which may or may not be ideal.

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.