gpt4 book ai didi

python - 将生成器转换为列表会覆盖 Python 中的值

转载 作者:太空宇宙 更新时间:2023-11-04 09:40:52 26 4
gpt4 key购买 nike

<分区>

我在 Python 3.5 中有这段代码,它实现了用于批处理可能较大的缓冲数据的生成器:

def batched_data(data, size=20):                             
batch = []
for d in data:
batch.append(d)
if len(batch) == size:
yield batch
batch.clear()
yield batch

def buffered_data(data, bufminsize=10, bufmaxsize=20):
diter = iter(data)
buffer = collections.deque(next(diter) for _ in range(bufmaxsize))

while buffer:
yield buffer.popleft()
if len(buffer) < bufminsize:
buffer.extend(
next(diter) for _ in range(bufmaxsize - len(buffer)))

def batched_buffered_data(data, bufsize=100, batch=20):
yield from batched_data(
buffered_data(data, bufmaxsize=bufsize,
bufminsize=bufsize - batch),
size=batch)

现在,当我初始化生成器并在 for 循环中遍历批处理时,一切都很好:

In [351]: gen = batched_buffered_data(range(27), bufsize=10, batch=7)
In [352]: for g in gen:
...: print(g)
...:
[0, 1, 2, 3, 4, 5, 6]
[7, 8, 9, 10, 11, 12, 13]
[14, 15, 16, 17, 18, 19, 20]
[21, 22, 23, 24, 25, 26]

但是,当我尝试使用列表理解或使用 list 进行转换时,会发生这种情况:

In [353]: gen = batched_buffered_data(range(27), bufsize=10, batch=7)

In [354]: list(gen)
Out[354]:
[[21, 22, 23, 24, 25, 26],
[21, 22, 23, 24, 25, 26],
[21, 22, 23, 24, 25, 26],
[21, 22, 23, 24, 25, 26]]

我真的很疑惑这个。一定涉及某种可变元素,但我真的不知道这种行为背后的原因。

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