条件和itertools.groupby问题

时间:2013-05-18 22:31:48

标签: python itertools

我正在使用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)

输出:

[]

这是为什么?

1 个答案:

答案 0 :(得分:3)

每个group都是可迭代的,并将其转换为列表会使其耗尽。您无法将可迭代变为列表两次

将列表存储为新变量:

for key, group in groupby(sorted(words, key = len), len):
    grouplist = list(group)
    if len(grouplist) > 1:
        print grouplist

现在只使用一次迭代:

>>> for key, group in groupby(sorted(words, key = len), len):
...     grouplist = list(group)
...     if len(grouplist) > 1:
...         print grouplist
... 
['this', 'that', 'them', 'what']