Python: how to sort a list by last character of a string

I am trying to write a program that arranges a list of strings based on the last character in an element.

["Tiger 6", "Shark 4", "Cyborg 8"] is how my list is imported, but I need to put them in numerical order based on the numbers at the end.

Thanks in advance!

+8
source share
4 answers

I am trying to write a program that arranges a list of strings based on the last character in an element.

 >>> s = ["Tiger 6", "Shark 4", "Cyborg 8"] >>> sorted(s, key=lambda x: int(x[-1])) ['Shark 4', 'Tiger 6', 'Cyborg 8'] 

Try this if there are more numbers lately.

 >>> import re >>> sorted(s, key=lambda x: int(re.search(r'\d+$',x).group())) ['Shark 4', 'Tiger 6', 'Cyborg 8'] 

re.search(r'\d+$',x).group() helps to get the number present in the latter, regardless of the previous space.

+13
source

If the numbers are not single numbers, you can try -

 >>> l = ["Tiger 6", "Shark 4", "Cyborg 8", "Temporary 12"] >>> l.sort(key = lambda x: int(x.rsplit(' ',1)[1])) >>> l ['Shark 4', 'Tiger 6', 'Cyborg 8', 'Temporary 12'] 
Function

str.rsplit(s, n) begins to split the line at the end to the beginning of the line and stops after n breaks. In the above case, it only breaks the string once in space.

+1
source
 def last_letter(word): return word[::-1] mylst = ["Tiger 6", "Shark 4", "Cyborg 8"] sorted(mylst, key=last_letter) 
0
source

Create a function that takes a string of words and returns a string sorted alphabetically by last character of each word in python?

-1
source

All Articles