gpt4 book ai didi

python - 无法在列表推导式之外检索 itertools 迭代器

转载 作者:行者123 更新时间:2023-12-04 09:26:56 25 4
gpt4 key购买 nike

考虑一下:

>>> res = [list(g) for k,g in itertools.groupby('abbba')]                                                                                                                                                           

>>> res
[['a'], ['b', 'b', 'b'], ['a']]
然后这个:
>>> res = [g for k,g in itertools.groupby('abbba')]

>>> list(res[0])
[]
我对此感到困惑。 为什么他们返回不同的结果吗?

最佳答案

这是预期的行为。 documentation很明显,石斑鱼的迭代器与 groupby 共享。迭代器:

The returned group is itself an iterator that shares the underlyingiterable with groupby(). Because the source is shared, when thegroupby() object is advanced, the previous group is no longer visible.So, if that data is needed later, it should be stored as a list...


您获得空列表的原因是迭代器在您尝试对其进行迭代时已被消耗。
import itertools 

res = [g for k,g in itertools.groupby('abbba')]

next(res[0])
# Raises StopIteration:

关于python - 无法在列表推导式之外检索 itertools 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62970993/

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