为什么 iter() 的副本指向相同的位置?
Why the copy of iter() pointing to the same location?
x=5
y=x
x=7
# Changing the value of x does not effect the value of y
作为一个简单的例子,x
&y
都有不同的内存位置,所以改变一个不会影响另一个
但是在下面的代码中 next(y)
给出了 4
为什么?
按照我的逻辑肯定是1
哪里出错了
a=[1,2,3,4,5,6,7,8,9,10]
x=iter(a)
y=x
print(next(x))
print(next(x))
print(next(x))
print(next(y))
执行 y=x
创建命名引用 y
,它基本上指向与变量 x
指向的相同内存位置,您可以使用 id
(它给出内存位置代表)内置验证它:
>>> a=[1,2,3,4,5,6,7,8,9,10]
>>> x=iter(a)
>>> y=x
>>> id(x)
1714277910984
>>> id(y)
1714277910984
如果您想要迭代器 x
的副本,您可以使用 copy
模块中的 deepcopy
函数:
>>> from copy import deepcopy
>>> y = deepcopy(x)
>>> id(x)
1714277910984
>>> id(y)
1714135198792
现在x
和y
是两个不同的迭代器:
>>> next(x)
1
>>> next(y)
1
>>> next(x)
2
>>> next(y)
2
在第一个例子中
x=5
y=x
x=7
第二行之后,x
和y
指向同一个对象,即5
。
当您更改 x
时,y
保持 5,因为您没有更改对象 5
本身,而只是更改了 x
指向的位置。然而,在第二个例子中,
a=[1,2,3,4,5,6,7,8,9,10]
x=iter(a)
y=x
print(next(x))
print(next(x))
print(next(x))
print(next(y))
x
和 y
仍然指向同一个位置。但是当您调用 next
方法时,您是在该位置更改对象,而不是在不同位置创建新对象。
x=5
y=x
x=7
# Changing the value of x does not effect the value of y
作为一个简单的例子,x
&y
都有不同的内存位置,所以改变一个不会影响另一个
但是在下面的代码中 next(y)
给出了 4
为什么?
按照我的逻辑肯定是1
哪里出错了
a=[1,2,3,4,5,6,7,8,9,10]
x=iter(a)
y=x
print(next(x))
print(next(x))
print(next(x))
print(next(y))
执行 y=x
创建命名引用 y
,它基本上指向与变量 x
指向的相同内存位置,您可以使用 id
(它给出内存位置代表)内置验证它:
>>> a=[1,2,3,4,5,6,7,8,9,10]
>>> x=iter(a)
>>> y=x
>>> id(x)
1714277910984
>>> id(y)
1714277910984
如果您想要迭代器 x
的副本,您可以使用 copy
模块中的 deepcopy
函数:
>>> from copy import deepcopy
>>> y = deepcopy(x)
>>> id(x)
1714277910984
>>> id(y)
1714135198792
现在x
和y
是两个不同的迭代器:
>>> next(x)
1
>>> next(y)
1
>>> next(x)
2
>>> next(y)
2
在第一个例子中
x=5
y=x
x=7
第二行之后,x
和y
指向同一个对象,即5
。
当您更改 x
时,y
保持 5,因为您没有更改对象 5
本身,而只是更改了 x
指向的位置。然而,在第二个例子中,
a=[1,2,3,4,5,6,7,8,9,10]
x=iter(a)
y=x
print(next(x))
print(next(x))
print(next(x))
print(next(y))
x
和 y
仍然指向同一个位置。但是当您调用 next
方法时,您是在该位置更改对象,而不是在不同位置创建新对象。