Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list by last character of string

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.

like image 276
Chris Hodges Avatar asked Jul 09 '15 02:07

Chris Hodges


People also ask

How do you sort a list with last character in Python?

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.

How do you sort a list by string length?

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.

How do you sort a list by string in Python?

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() .


2 Answers

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.

like image 155
Avinash Raj Avatar answered Sep 17 '22 14:09

Avinash Raj


def last_letter(word):
    return word[::-1]

mylst = ["Tiger 6", "Shark 4", "Cyborg 8"]
sorted(mylst, key=last_letter)
like image 34
ronith raj Avatar answered Sep 21 '22 14:09

ronith raj