-1

I tried to sort a list of strings that are actually integers, but I do not get the right sort value. How do I sort it in a way that it is sorted according to the integer values of the string?

a = ['10', '1', '3', '2', '5', '4']
print(sorted(a))

Output:

['1', '10', '2', '3', '4', '5']

Output wanted:

['1', '2', '3', '4', '5', '10']
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ashim
  • 877
  • 2
  • 12
  • 22
  • 1
    `a.sort(key=int)` Possible duplicate of [How to sort python list of strings of numbers](https://stackoverflow.com/q/17474211/11568368) – Vanshika Mar 16 '20 at 03:28
  • Also *[How to sort a list of strings numerically](https://stackoverflow.com/questions/3426108/how-to-sort-a-list-of-strings-numerically)* (2010) – Peter Mortensen Jul 31 '23 at 20:17

4 Answers4

5

We have to use the lambda as a key and make each string to int before the sorted function happens.

sorted(a,key=lambda i: int(i))

Output :
     ['1', '2', '3', '4', '5', '10']

More shorter way -> sorted(a,key=int). Thanks to @Mark for commenting.

teddcp
  • 1,514
  • 2
  • 11
  • 25
  • 2
    I think this is the right approach. FWIW, you can simply to `sorted(a,key=int)` and avoid the lambda. – Mark Mar 16 '20 at 03:27
  • 1
    @MarkMeyer, Wow..that's even shorter!!.. never had thought of this. Thanks – teddcp Mar 16 '20 at 03:29
1

You could convert the strings to integers, sort them, and then convert back to strings. Example using list comprehensions:

sorted_a = [str(x) for x in sorted(int(y) for y in a)]

More verbose version:

int_a = [int(x) for x in a]  # Convert all elements of a to ints
sorted_int_a = sorted(int_a)  # Sort the int list
sorted_str_a = [str(x) for x in sorted_int_a]  # Convert all elements of int list to str

print(sorted_str_a)

Note: @tedd's solution to this problem is the preferred solution to this problem, I would definitely recommend that over this.

Oliver.R
  • 1,282
  • 7
  • 17
1

So one of the ways to approach this problem is converting the list to a list integers by iterating through each element and converting them to integers and later sort it and again converting it to a list of strings again.

0

Whenever you have a list of elements and you want to sort using some property of the elements, use key argument (see the docs).

Here's what it looks like:

>>> a = ['10', '1', '3', '2', '5', '4']
>>> print(sorted(a))
['1', '10', '2', '3', '4', '5']
>>> print(sorted(a, key=lambda el: int(el)))
['1', '2', '3', '4', '5', '10']
Pavel Vergeev
  • 3,060
  • 1
  • 31
  • 39