传递给发电机的复制列表反映了对原始的更改
在回答
from typing import List, Iterable
class Name:
def __init__(self, name: str):
self.name = name
def generator(lst: List[Name]) -> Iterable[str]:
lst_copy = lst.copy()
for obj in lst_copy:
yield obj.name
时进行的,对原始列表的更改仍然反映:
lst = [Name("Tom"), Name("Tommy")]
gen = generator(lst)
lst[0] = Name("Andrea")
for name in gen:
print(name)
输出:
Andrea
Tommy
简单地返回发电机表达式按预期工作:
def generator(lst: List[Name]) -> Iterable[str]:
return (obj.name for obj in lst.copy())
输出:
Tom
Tommy
为什么第一个生成器函数在第一个生成器函数中lst.copy()为什么不按预期工作?
In answering this question, I stumbled across some unexpected behavior:
from typing import List, Iterable
class Name:
def __init__(self, name: str):
self.name = name
def generator(lst: List[Name]) -> Iterable[str]:
lst_copy = lst.copy()
for obj in lst_copy:
yield obj.name
When modifying the list that is passed to the generator, even though a copy is made, changes to the original list are still reflected:
lst = [Name("Tom"), Name("Tommy")]
gen = generator(lst)
lst[0] = Name("Andrea")
for name in gen:
print(name)
Output:
Andrea
Tommy
Simply returning a generator expression works as expected:
def generator(lst: List[Name]) -> Iterable[str]:
return (obj.name for obj in lst.copy())
Output:
Tom
Tommy
Why doesn't the lst.copy()
in the first generator function work as expected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为,最好通过增加一些额外的打印语句来理解这种行为:
请注意,副本不会在分配时间发生 - 在之后,列表被修改了!
在发电机的身体中执行,直到循环尝试提取元素之前。由于这种提取尝试是在列表突变之后发生的,因此突变反映在发电机的结果中。
I think the behavior is best understood with the addition of some extra print statements:
Notice that the copy does not happen at assignment time -- it happens after the list is modified!
Nothing in the generator's body is executed until the
for
loop attempts to extract an element. Since this extraction attempt occurs after the list is mutated, the mutation is reflected in the results from the generator.在请求第一项之前,发电机的主体不会开始执行。因此,在此代码中:
...首先,执行
lst [0] =名称(“ Andrea”)
。然后,您有一个循环的,它开始执行发电机。那是执行
lst_copy = lst.copy()
,这为时已晚,无法在lst [0]
sistigment之前进入。发电机表达式起作用,因为在创建迭代器之前,必须评估发电机(
lst.copy()
,最后一部分)的迭代部分。The body of a generator does not start executing until the first item is requested. So in this code:
... First, the
lst[0] = Name("Andrea")
is executed. Then, you have afor
loop, which starts executing the generator. That's whenlst_copy = lst.copy()
is executed, which is too late to get in before thelst[0]
assignment.The generator expression works, because the iterable portion of the generator (
lst.copy()
, the last part) must be evaluated before creating the iterator.