1

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

输出:

[]

为什么是这样?

4

1 回答 1

4

每个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']
于 2013-05-18T22:32:54.707 回答