I am trying to write a program that orders a list of strings based on the last character in the item.
["Tiger 6", "Shark 4", "Cyborg 8"]
are how my list is imported, but I need to put them in numerical order based on the numbers at the end.
You can sort using a function, here we use the lambda function which looks at the last index of the strings inside of your list. Without making a copy of the list you can apply the . sort() . This is a more memory efficient method.
Custom Sorting With key= For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest. The sort calls len() for each string to get the list of proxy length values, and then sorts with those proxy values.
In Python, there are two ways, sort() and sorted() , to sort lists ( list ) in ascending or descending order. If you want to sort strings ( str ) or tuples ( tuple ), use sorted() .
I am trying to write a program that orders a list of strings based on the last character in the item.
>>> 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 num of digits at the last.
>>> 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 fetch the number present at the last irrespective of preceding space.
def last_letter(word):
return word[::-1]
mylst = ["Tiger 6", "Shark 4", "Cyborg 8"]
sorted(mylst, key=last_letter)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With