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.
source share