Python 条件句和itertools.groupby问题

Python 条件句和itertools.groupby问题,python,itertools,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', 'tha

我使用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)
输出:

[]
为什么会这样

每个组都是一个iterable,把它变成一个列表会耗尽它。不能将iterable转换为列表两次

将列表存储为新变量:

for key, group in groupby(sorted(words, key = len), len):
    grouplist = list(group)
    if len(grouplist) > 1:
        print grouplist
现在,您只需使用iterable一次:

>>> for key, group in groupby(sorted(words, key = len), len):
...     grouplist = list(group)
...     if len(grouplist) > 1:
...         print grouplist
... 
['this', 'that', 'them', 'what']
每个组都是一个iterable,把它变成一个列表会让它筋疲力尽。不能将iterable转换为列表两次

将列表存储为新变量:

for key, group in groupby(sorted(words, key = len), len):
    grouplist = list(group)
    if len(grouplist) > 1:
        print grouplist
现在,您只需使用iterable一次:

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

@JumBopap:仍然只迭代一次,存储结果,对其进行测试。@JumBopap:仍然只迭代一次,存储结果,对其进行测试。