[英]Forcing a list out of a generator
>>>def change(x):
... x.append(len(x))
... return x
>>>a=[]
>>>b=(change(a) for i in range(3))
>>>next(b)
[0]
>>>next(b)
[0,1]
>>>next(b)
[0,1,2]
>>>next(b)
Traceback ... StopIteration
>>>a=[]
>>>b=(change(a) for i in range(3))
>>>list(b) #expecting [[0],[0,1],[0,1,2]]
[[0,1,2],[0,1,2],[0,1,2]]
So I was just testing my understanding of generators and messing around with the command prompt and now I'm unsure if I actually understand how generators work. 因此,我只是测试了我对生成器的理解,并弄乱了命令提示符,现在不确定我是否真正了解生成器的工作原理。
The problem is that all calls to change(a)
return the same object (in this case, the object is the value of a
), but this object is mutable and changes its value. 问题是,所有呼叫
change(a)
返回相同的对象 (在这种情况下,对象的值a
),但这个对象是可变的,改变其值。 An example of the same problem without using generators: 不使用生成器的相同问题的示例:
a = []
b = []
for i in range(3):
a.append(len(a))
b.append(a)
print b
If you want to avoid it, you need to make a copy of your object (for example, make change
return x[:]
instead of x
). 如果要避免这种情况,则需要制作对象的副本(例如,使
change
返回x[:]
而不是x
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.