简体   繁体   English

按长度和最后 N 个字符对字符串列表进行排序

[英]Sorting list of strings by their length and the last N characters

I'm trying to solve a problem, where I have to sort a list of strings by the length of the string as well as the last characters in the string.我正在尝试解决一个问题,我必须按字符串的长度以及字符串中的最后一个字符对字符串列表进行排序。 In the case of the string having the same length and same last character, they should be sorted by second to last character and so on.如果字符串长度相同,最后一个字符相同,则应按倒数第二个字符排序,依此类推。

I have this code, but I'm not clear on why it does not work as I intend.我有这个代码,但我不清楚为什么它不能按我的意图工作。 Could someone point me in the right direction?有人能指出我正确的方向吗?

My code:我的代码:

import sys

word_lists = [line.split(' ') for line in ' '.join([x.strip() for x in sys.stdin.readlines()]).split('  ')]
for i in range(0, len(word_lists)):
    word_lists[i] = sorted((word_lists[i]), key=lambda x: (x[:-1], len(x)))

Input:输入:

apple
banana
grape
kiwi
pear

airplane
bicycle
boat
car

Output:输出:

[['apple', 'banana', 'grape', 'kiwi', 'pear'], ['airplane', 'bicycle', 'boat', 'car']]

Expected Output:预期输出:

[['banana', 'apple', 'grape', 'kiwi', 'pear'], ['bicycle', 'airplane', 'car', 'boat']]

Use x[::-1] .使用x[::-1]

Ex:前任:

l = [['apple', 'banana', 'grape', 'kiwi', 'pear'], ['airplane', 'bicycle', 'boat', 'car']]
for i in l:
    print(sorted(i, key=lambda x: (x[::-1], len(x))))

Output:输出:

['banana', 'apple', 'grape', 'kiwi', 'pear']
['bicycle', 'airplane', 'car', 'boat']

output = [sorted(i, key=lambda x: (x[::-1], len(x))) for i in l]
print(output)
--> [['banana', 'apple', 'grape', 'kiwi', 'pear'], ['bicycle', 'airplane', 'car', 'boat']]

如果您想首先按字符串长度对数据进行排序,那么您必须更改代码中的键顺序,并且您希望您的字符串按字母顺序从尾部排序,因此您必须从尾部 (x[::-1]) 发送字符,所以最后您必须通过 key(len(x), x[::-1]) 更改您的密钥

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM