[英]Temporary created during python list iteration?
I want to understand why the following is happening. 我想了解为什么会发生以下情况。 My guess is that a temporary is being created during list iteration, but want some experts to confirm this: 我的猜测是在列表迭代期间正在创建临时,但是需要一些专家来确认:
def test():
a=[set([1,2,3]),set([3,4,5])]
x=set([1,4])
for i in a:
# doesn't actually modify list contents, making a copy of list elements in i?
i=i.difference(x)
print a
for idx,i in enumerate(a):
i=i.difference(x)
print id(i),id(a[idx])
# obviously this modifies the contents
a[idx]=i
print a
Output: 输出:
[set([1, 2, 3]), set([3, 4, 5])]
59672976 59672616
59672616 59672736
[set([2, 3]), set([3, 5])]
Also, I want to understand why the "id" of i in the second iteration is the same as the "id" for a[0]. 另外,我想理解为什么第二次迭代中i的“id”与[0]的“id”相同。
It helps to look at this graphically, because it's basically a pointer problem. 它有助于以图形方式查看,因为它基本上是一个指针问题。
for i in a
iteratively assigns i
to each element in a
. for i in a
迭代分配i
在每个元件a
。
i = i.difference(x)
creates i = i.difference(x)
创建 and assigns i
to it. 并指派i
。
Let's take this one step at a time: 让我们一步一步:
i.difference(x)
doesn't modify i
or x
. i.difference(x)
不会修改i
或x
。 Rather, it returns a new set. 相反,它返回一个新集。 i = i.difference(x)
rebinds the variable i
to point to the new set. i = i.difference(x)
重新绑定变量i
以指向新集合。 It does not affect the contents of the list in any way. 它不会以任何方式影响列表的内容。 a[idx] = i
does modify the list by setting its idx
-th element to the new set. a[idx] = i
确实通过将其idx
-th元素设置为新集来修改列表。 A cleaner implementation might use a different variable instead of re-purposing i
: 更干净的实现可能使用不同的变量而不是重新使用i
:
def test():
a=[set([1,2,3]),set([3,4,5])]
x=set([1,4])
for i in a:
diff=i.difference(x)
# a[idx]=diff
print a
Yes, when you execute i=i.difference(x)
it creates a new i
. 是的,当你执行i=i.difference(x)
它会创建一个新的i
。 Just modify your code like this to understand what is happening - 只需像这样修改你的代码就可以了解发生了什么 -
def test():
a=[set([1,2,3]),set([3,4,5])]
x=set([1,4])
for i in a:
# doesn't actually modify list contents, making a copy of list elements in i?
print 'old i - ', id(i)
i=i.difference(x)
print 'new i - ', id(i)
print a
test()
Output - 输出 -
old i - 4467059736
new i - 4467179216
old i - 4467177360
new i - 4467179216
[set([1, 2, 3]), set([3, 4, 5])]
Your use of set.difference() suggests that you don't know the operator -=
for sets: 你使用set.difference()表明你不知道运算符-=
for sets:
def test():
a=[set([1,2,3]),set([3,4,5])]
x=set([1,4])
for i in a:
i -= x
print a
This shows that i
is just another pointer to the set you want to modify. 这表明i
只是指向要修改的集合的另一个指针。 Just don't overwrite your pointer! 只是不要覆盖你的指针!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.