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

标签 python python-2.7

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

[[],['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/

相关文章:

Linux 上的 Python .pyd 等价物

python - OpenCV - imread()、imwrite() 增加了 png 的大小?

python - 匹配字符串末尾的模式?

python - 如何在 while 循环中每行显示 5 个数字

python - 用 C 扩展 python,返回 numpy 数组给出垃圾

json - 从 JSON 字符串中删除反斜杠?

python - 将字符串转换为字典 python

python - 在类中生成动态方法

python - 我无法弄清楚这个时间戳的含义

python - 有没有办法提高循环速度,或者在不使用 for 循环的情况下以更快的方式做同样的事情?