在代码中
y = 7
x = y
x = 8
Run Code Online (Sandbox Code Playgroud)
现在,y将是7,x将是8.但实际上我想改变y.我可以指定y的参考并执行此操作吗?
例如,在C++中可以实现同样的目的,
int y = 8;
int &x = y;
x = 9;
Run Code Online (Sandbox Code Playgroud)
现在y&x都是9
这是一个有效的python行为吗?我认为最终结果应该是[0,0,0]并且id()函数应该在每次迭代时返回相同的值.如何使它成为pythonic,而不是使用枚举或范围(len(bar))?
bar = [1,2,3]
print bar
for foo in bar:
print id (foo)
foo=0
print id(foo)
print bar
Run Code Online (Sandbox Code Playgroud)
输出:
[1, 2, 3]
5169664
5169676
5169652
5169676
5169640
5169676
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)