根据最后3个字符对文本进行排序 [英] Sort text based on last 3rd character
问题描述
我正在使用sorted()函数根据最后一个字符对文本进行排序 完美的
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]
return sorted(strings,key=last_letter)
print(sort_by_last_letter(["hello","from","last","letter","a"]))
输出
['a', 'from', 'hello', 'letter', 'last']
我的要求是根据最后3个字符进行排序.但是问题是少于3个字符的单词很少,因此应该根据下一个较低的字符进行排序(如果存在则为2个,否则为最后一个).它以pythonic方式
My requirement is to sort based on last 3rd character .But problem is few of the words are less than 3 character in that case it should be sorted based on next lower placed character (2 if present else last).Searching to do it in pythonic way
目前我正在
IndexError:字符串索引超出范围
IndexError: string index out of range
def sort_by_last_letter(strings):
def last_letter(s):
return s[-3]
return sorted(strings,key=last_letter)
print(sort_by_last_letter(["hello","from","last","letter","a"]))
推荐答案
您可以使用:
return sorted(strings,key=lambda x: x[max(0,len(x)-3)])
因此,我们首先计算字符串len(x)
的长度,然后从中减去3
.如果字符串不是那么长,我们将因此获得一个负索引,但是通过使用max(0,..)
,我们可以防止出现这种情况,因此可以使用最后一个但不包括一个或最后一个字符(如果不存在这些字符).
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']
如果您不在乎抢七彩(换句话说,如果可以重新排序'a'
和'abc'
),则可以使用更优雅的方法:
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
return sorted(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)
这篇关于根据最后3个字符对文本进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!