列表操作后Groupby对象消失

Bao*_* Le 5 python run-length-encoding

我正在尝试游程编码问题,在运行 groupby & list 操作后,我的 groupby 对象以某种方式消失了。

import itertools
s = 'AAAABBBCCDAA'
for c, group in itertools.groupby(s):
    print(list(group))
    print(list(group))
Run Code Online (Sandbox Code Playgroud)

我的输出是

['A', 'A', 'A', 'A']
[]
['B', 'B', 'B']
[]
['C', 'C']
[]
['D']
[]
['A', 'A']
[]
Run Code Online (Sandbox Code Playgroud)

因此对于每个循环,两个打印命令会产生不同的结果。

有人可以帮助解释我做错了什么吗?

U10*_*ard 3

因为有发电机,用完后就消失了:

>>> a = iter([1, 2, 3])
>>> list(a)
[1, 2, 3]
>>> list(a)
[]
Run Code Online (Sandbox Code Playgroud)

为了留住他们:

import itertools
s = 'AAAABBBCCDAA'
for c, group in itertools.groupby(s):
    l = list(group)
    print(l)
    print(l)
Run Code Online (Sandbox Code Playgroud)

输出:

['A', 'A', 'A', 'A']
['A', 'A', 'A', 'A']
['B', 'B', 'B']
['B', 'B', 'B']
['C', 'C']
['C', 'C']
['D']
['D']
['A', 'A']
['A', 'A']
Run Code Online (Sandbox Code Playgroud)