gpt4 book ai didi

python - 条件和 itertools.groupby 问题

转载 作者:行者123 更新时间:2023-11-30 21:50:30 27 4
gpt4 key购买 nike

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

输出:

[]

这是为什么呢?

最佳答案

每个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']

关于python - 条件和 itertools.groupby 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16629607/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com