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?
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?
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']