Skip to content Skip to sidebar Skip to footer

Sort Text Based On Last 3rd Character

I am using the sorted() function to sort the text based on last character which works perfectly def sort_by_last_letter(strings): def last_letter(s): return s[-1] r

Solution 1:

You can use:

returnsorted(strings,key=lambda x: x[max(0,len(x)-3)])

So thus we first calculate the length of the string len(x) and subtract 3 from it. In case the string is not that long, we will thus obtain a negative index, but by using max(0,..) we prevent that and thus take the last but one, or the last character in case these do not exist.

This will work given every string has at least one character. This will produce:

>>> sorted(["hello","from","last","letter","a"],key=lambda x: x[max(0,len(x)-3)])
['last', 'a', 'hello', 'from', 'letter']

In case you do not care about tie-breakers (in other words if 'a' and 'abc' can be reordered), you can use a more elegant approach:

from operator import itemgetter

returnsorted(strings,key=itemgetter(slice(-3,None)))

What we here do is generating a slice with the last three characters, and then compare these substrings. This then generates:

>>> sorted(strings,key=itemgetter(slice(-3,None)))
['a', 'last', 'hello', 'from', 'letter']

Since we compare with:

['a', 'last', 'hello', 'from', 'letter']
#  ['a',  'ast',   'llo',  'rom',    'ter'] (comparison key)

Solution 2:

You can simply use the minimum of the string length and 3:

defsort_by_last_letter(strings):
    deflast_letter(s):
        return s[-min(len(s), 3)]
    returnsorted(strings,key=last_letter)

print(sort_by_last_letter(["hello","from","last","letter","a"]))

Post a Comment for "Sort Text Based On Last 3rd Character"