例如,我有一个清单,比方说
list = ['sight', 'first', 'love', 'was', 'at', 'It']
Run Code Online (Sandbox Code Playgroud)
我想按字长对这个列表进行分组
newlist = [['sight', 'first'],['love'], ['was'], ['at', 'It']]
Run Code Online (Sandbox Code Playgroud)
请帮帮我.升值!
用途itertools.groupby
:
>>> from itertools import groupby
>>> lis = ['sight', 'first', 'love', 'was', 'at', 'It']
>>> [list(g) for k, g in groupby(lis, key=len)]
[['sight', 'first'], ['love'], ['was'], ['at', 'It']]
Run Code Online (Sandbox Code Playgroud)
请注意,为了itertools.groupby
正常工作,所有项目必须按长度排序,否则请先使用collections.defaultdict
(O(N)
)或排序列表,然后使用itertools.groupby
(O(NlogN)
).:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> lis = ['sight', 'first', 'foo', 'love', 'at', 'was', 'at', 'It']
>>> for x in lis:
... d[len(x)].append(x)
...
>>> d.values()
[['at', 'at', 'It'], ['foo', 'was'], ['love'], ['sight', 'first']]
Run Code Online (Sandbox Code Playgroud)
如果您希望对最终输出列表进行排序,则可以按长度更好地对列表项进行排序并应用于该列表项itertools.groupby
.
您可以使用临时字典然后按长度排序:
li=['sight', 'first', 'love', 'was', 'at', 'It']
d={}
for word in li:
d.setdefault(len(word), []).append(word)
result=[d[n] for n in sorted(d, reverse=True)]
print result
# [['sight', 'first'], ['love'], ['was'], ['at', 'It']]
Run Code Online (Sandbox Code Playgroud)
您可以使用 defaultdict:
from collections import defaultdict
d=defaultdict(list)
for word in li:
d[len(word)].append(word)
result=[d[n] for n in sorted(d, reverse=True)]
print result
Run Code Online (Sandbox Code Playgroud)
或__missing__
像这样使用:
class Dicto(dict):
def __missing__(self, key):
self[key]=[]
return self[key]
d=Dicto()
for word in li:
d[len(word)].append(word)
result=[d[n] for n in sorted(d, reverse=True)]
print result
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1475 次 |
最近记录: |