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

时间:2015-02-10 07:02:23

标签: python python-2.7

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

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

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

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

但我想要的是按长度排序,具有相同长度的那些必须按字母顺序排序。即'低'<'星期一'所以输出应该是:

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

我必须使用哪种密钥才能使用内置排序进行排序?

编辑:但如果输入是混合的情况怎么办?如果是:

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

,所需的输出将是:

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

2 个答案:

答案 0 :(得分:1)

首先按字母顺序排序,然后按相反顺序排序。

>>> lst = [['hi', 'monday'], [], ['hello', 'indent', 'joe'], ['hi', 'low']]
>>> lst.sort()
>>> lst.sort(key=len, reverse=True)
>>> print lst
>>> [['hello', 'indent', 'joe'], ['hi', 'low'], ['hi', 'monday'], []]

结果集中的项目顺序高度取决于您当前的区域设置。如果您希望排序算法在排序项时考虑区域设置,则可以执行以下操作;

>>> import locale
>>> from functools import cmp_to_key
>>>
>>> # You can change your locale like below;
>>> # locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
>>>
>>> lst = [['hi', 'monday'], [], ['hello', 'indent', 'joe'], ['hi', 'low']]
>>> print sorted([sorted(item, key=cmp_to_key(locale.strcoll)) for item in lst], key=len, reverse=True)
>>> [['hello', 'indent', 'joe'], ['hi', 'monday'], ['hi', 'low'], []]

答案 1 :(得分:1)

这可以通过合适的键功能一次完成。

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'], []]
相关问题