Skip to main content
 首页 » 编程设计

python之对列表中的一组单词进行排序

2024年10月25日10grandyang

我知道按长度对包含单词的列表列表进行排序。 这意味着一个列表:

[[],['hello','indent'],['hi','monday'],['hi','low']] 

如果排序键为 length 且 reverse 为 True,则结果:

[['hello','indent','joe'],['hi','monday'],['hi','low'],[]] 

但我想要的是同时按长度排序,并且具有相同长度的必须按字母顺序排序。即 'low'<'monday' 所以输出应该是:

[['hello','indent','joe'],['hi','low'],['hi','monday'],[]] 

我必须使用哪种键来使用内置排序进行排序?

编辑:但是如果输入是大小写混合的呢?如果是怎么办:

[['嗨', '星期一'], [], ['你好', '缩进', '乔'], ['嗨', '低']]

所需的输出将是:

[['hello', 'indent', 'joe'], ['hi', 'monday'],['Hi', 'low'], []] 

请您参考如下方法:

这可以通过适当的键函数一次性完成。

a = [['hi', 'monday'], [], ['hello', 'indent', 'joe'], ['hi', 'low']] 
a.sort(key=lambda l:(-len(l), l)) 
print a 

输出

[['hello', 'indent', 'joe'], ['hi', 'low'], ['hi', 'monday'], []] 

要让小写字母排在大写字母之前,我们可以简单地对每个子列表中的字符串使用 str.swapcase() 方法:

a = [['Hi', 'monday'], [], ['hello', 'indent', 'joe'], ['hi', 'low']] 
a.sort(key=lambda l:(-len(l), [s.swapcase() for s in l])) 
print a 

输出

[['hello', 'indent', 'joe'], ['hi', 'low'], ['Hi', 'monday'], []] 

如果您希望排序不区分大小写:

a = [['Hi', 'monday'], [], ['hello', 'indent', 'joe'], ['hi', 'low']] 
a.sort(key=lambda l:(-len(l), [s.lower() for s in l])) 
print a 

输出

[['hello', 'indent', 'joe'], ['hi', 'low'], ['Hi', 'monday'], []]