我知道按长度对包含单词的列表进行排序。 这意味着一个列表:
[[],['hello','indent'],['hi','monday'],['hi','low']]
如果排序键为 length 且反向为 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'], []]
关于python - 对列表中的一组单词进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28425880/