2015-02-10 76 views
2

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

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

这导致如果排序的关键是长度,情况正好相反:

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

你应该使用相同的'的.sort()'它会隐生成期望的输出我猜 – ZdaR 2015-02-10 07:06:49

+1

你可以尝试制作一个自定义函数并将它传递给'key'。 – 2015-02-10 07:08:52

回答

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

在小写字母的情况下似乎是完美的,但如果输入是混合大小写呢?如果它是[['Hi','monday'],[],['hello','indent','joe'],['hi','low']]并且期望的输出将是: [['hello','indent','joe'],['hi','monday'],['Hi','low'],[]] – 2015-02-10 09:22:29

+0

@galipremsagar:这有点复杂这是因为大写字母在默认ASCII归类顺序中的小写字母前面。例如'ord('H')== 72'和'ord('h')== 104'。幸运的是,我们可以通过一个简单的技巧来解决这个问题。 – 2015-02-10 09:55:38

+0

根据不区分大小写的顺序,按列表长度和字母顺序排序的技巧或关键是什么? – 2015-02-10 09:58:10

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