列表操作后Groupby对象消失
Groupby object disappears after list operation
我正在尝试 运行 长度编码问题,在 运行 进行 groupby 和列表操作后,我的 groupby 对象不知何故消失了。
import itertools
s = 'AAAABBBCCDAA'
for c, group in itertools.groupby(s):
print(list(group))
print(list(group))
我的输出是
['A', 'A', 'A', 'A']
[]
['B', 'B', 'B']
[]
['C', 'C']
[]
['D']
[]
['A', 'A']
[]
因此对于每个循环,2 个打印命令会产生不同的结果。
谁能帮我解释一下我做错了什么?
因为有发电机,用完就没了:
>>> a = iter([1, 2, 3])
>>> list(a)
[1, 2, 3]
>>> list(a)
[]
要保留它们:
import itertools
s = 'AAAABBBCCDAA'
for c, group in itertools.groupby(s):
l = list(group)
print(l)
print(l)
输出:
['A', 'A', 'A', 'A']
['A', 'A', 'A', 'A']
['B', 'B', 'B']
['B', 'B', 'B']
['C', 'C']
['C', 'C']
['D']
['D']
['A', 'A']
['A', 'A']
groupby
函数 returns 一个在您调用 list(group)
时使用的迭代器。
"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." docs.
我正在尝试 运行 长度编码问题,在 运行 进行 groupby 和列表操作后,我的 groupby 对象不知何故消失了。
import itertools
s = 'AAAABBBCCDAA'
for c, group in itertools.groupby(s):
print(list(group))
print(list(group))
我的输出是
['A', 'A', 'A', 'A']
[]
['B', 'B', 'B']
[]
['C', 'C']
[]
['D']
[]
['A', 'A']
[]
因此对于每个循环,2 个打印命令会产生不同的结果。
谁能帮我解释一下我做错了什么?
因为有发电机,用完就没了:
>>> a = iter([1, 2, 3])
>>> list(a)
[1, 2, 3]
>>> list(a)
[]
要保留它们:
import itertools
s = 'AAAABBBCCDAA'
for c, group in itertools.groupby(s):
l = list(group)
print(l)
print(l)
输出:
['A', 'A', 'A', 'A']
['A', 'A', 'A', 'A']
['B', 'B', 'B']
['B', 'B', 'B']
['C', 'C']
['C', 'C']
['D']
['D']
['A', 'A']
['A', 'A']
groupby
函数 returns 一个在您调用 list(group)
时使用的迭代器。
"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." docs.