我知道要对包含单词长度的列表列表进行排序。这意味着一个清单:
[[],['hello','indent'],['hi','monday'],['hi','low']]
如果排序键是length,而反向则为True,则结果为:
[['hello','indent','joe'],['hi','monday'],['hi','low'],[]]
但是我想要的是按长度排序,而长度相同的必须按字母顺序排序。即,'low'<'monday',因此输出应为:
[['hello','indent','joe'],['hi','low'],['hi','monday'],[]]
我必须使用哪种密钥来进行内置排序?
编辑:但是如果输入是混合大小写怎么办?如果是这样的话:
[['Hi', 'monday'], [], ['hello', 'indent', 'joe'], ['hi', 'low']]
所需的输出将是:
[['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'], []]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句