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
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']
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']
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