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

标签 python python-3.x python-itertools

考虑一下:

>>> 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 underlying iterable with groupby(). Because the source is shared, when the groupby() 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/

相关文章:

python - Pandas 数据框 : how to permute rows and create new groups of combinations

python - 读取文本文件中行的进度条

python - 在 Pandas 中,如何在 DataFrame 中排在前十组数据?

r - 我们可以使用 pandas dataframe 创建一个困惑的表吗?

linux - python 将 os.environ 传递给子 gnome 终端

Python 使用 itertools.product 创建列表?

Python:从负 Y 值开始的 Matplotlib 条形图

python - 获取包含字符串元素的列表,不包括以初始列表中的任何其他元素为前缀的元素

python - 非线性决策边界的 SVM 图

python - 优化非常慢的排列搜索循环(不能使用 itertools)。有什么建议么?