-1

I just started playing with a list and would like to know.

If I have a data in a list in a format ['John 1', 'Jack 2']

How to sort them by the number?

Ffisegydd
  • 51,807
  • 15
  • 147
  • 125

2 Answers2

1

You can pass a key to the sorted function which extracts the number by splitting on the space and then converts it to an integer.

a = ['John 2', 'Jack 1']

print(sorted(a, key=lambda x:int(x.split(' ')[-1])))
# ['Jack 1', 'John 2']
Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
  • Can you please show me how to sort list in a opposite way? mylist =['Jack 1', 'John 2'] and i want to get ['John 2', 'Jack 1'] – Zeleny pan Dec 16 '14 at 15:54
  • @Zelenypan you can instead use the `reversed` function to sort something in the "opposite" direction. Or you can pass `reverse=True` to `a.sort(reverse=True)`. – Ffisegydd Dec 16 '14 at 15:54
0

list.sort, sorted accept optional key parameter. The return value of the function will be used as comparison key.

>>> sorted(['John 1', 'Jedi 3', 'Jack 2'], key=lambda x: int(x.split()[-1]))
['John 1', 'Jack 2', 'Jedi 3']
falsetru
  • 357,413
  • 63
  • 732
  • 636