我正在使用 groupby 来解析单词列表并按长度将它们组织成列表。例如:
from itertools import groupby
words = ['this', 'that', 'them', 'who', 'what', 'where', 'whyfore']
for key, group in groupby(sorted(words, key = len), len):
print key, list(group)
3 ['who']
4 ['this', 'that', 'them', 'what']
5 ['where']
7 ['whyfore']
获取列表的长度也可以:
for key, group in groupby(sorted(words, key = len), len):
print len(list(group))
1
4
1
1
如果我像这样预先设置条件,则结果如下:
for key, group in groupby(sorted(words, key = len), len):
if len(list(group)) > 1:
print list(group)
输出:
[]
为什么是这样?