考虑一下:
>>> 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/