Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of strings by second-to-last character

I need to sort a list of strings using character comparison starting with penultimate element moving down to the beginning of string (for equal characters). so basically I need to get this

in_ = ['message', 'essagem', 'ssageme', 'sagemes', 'agemess', 'gemessa', 'emessag']

result = ['emessag', 'essagem', 'sagemes', 'message', 'ssageme', 'agemess', 'gemessa']
# sorted on second to last character in each string
like image 247
empty lungs Avatar asked Dec 24 '22 13:12

empty lungs


2 Answers

Is this what you want? If yes, make that penultimate letter the key for the sort() function.

a = ['message', 'essagem', 'ssageme', 'sagemes', 'agemess', 'gemessa', 'emessag']
a.sort(key=lambda x:x[-2])
print(a)

Output:

['emessag', 'essagem', 'sagemes', 'message', 'ssageme', 'agemess', 'gemessa']
like image 95
Miraj50 Avatar answered Jan 09 '23 15:01

Miraj50


Just to add something alternative to Miraj50's answer: You can do it using itemgetter too in a bit cleaner/faster way.

from operator import itemgetter

in_list = ['message', 'essagem', 'ssageme', 'sagemes', 'agemess', 'gemessa', 'emessag']
result = sorted(in_list, key=itemgetter(-2))
print(result)

output:

['emessag', 'essagem', 'sagemes', 'message', 'ssageme', 'agemess', 'gemessa']
like image 42
utengr Avatar answered Jan 09 '23 17:01

utengr