I have a list
['2,alex', '5,james', '3,ben']
I need to alphabetically sort this.
The output should be
['2,alex', '3,ben', '5,james']
However using the .sort
function does not work and will only sort it in a numerical order.
You can give list.sort()
a key like below. If you want sort by the number, you can just use str.split(',')[0]
to get it, and convert it to an integer:
>>> l = ['2,alex', '5,james', '3,ben']
>>> l.sort(key=lambda x: int(x.split(',')[0]))
>>> l
['2,alex', '3,ben', '5,james']
If you need sort it by name, not the number, just use the same way but replace [0]
with [1]
, and remove the int()
function:
>>> l = ['2,alex', '5,james', '3,ben']
>>> l.sort(key=lambda x: x.split(',')[1])
>>> l
['2,alex', '3,ben', '5,james']
Let's see a clear example:
>>> sorted(l, key=lambda x: int(x.split(',')[0]))
['5,james', '10,ben', '22,alex']
>>> sorted(l, key=lambda x: x.split(',')[1])
['22,alex', '10,ben', '5,james']