gpt4 book ai didi

Python "a=a-b"和 "a-=b"真的等价吗?

转载 作者:太空宇宙 更新时间:2023-11-03 12:28:30 25 4
gpt4 key购买 nike

似乎 a = a-ba -= b 不同,我不知道为什么。

代码:

cache = {}
def part(word):
if word in cache:
return cache[word]
else:
uniq = set(word)
cache[word] = uniq
return uniq

w1 = "dummy"
w2 = "funny"

# works
test = part(w1)
print(test)
test = test-part(w2)
print(test)
print(cache)

# dont't works
test = part(w1)
print(test)
test -= part(w2) # why it touches "cache"?
print(test)
print(cache)

结果:

set(['y', 'm', 'u', 'd'])
set(['m', 'd'])
{'dummy': set(['y', 'm', 'u', 'd']), 'funny': set(['y', 'n', 'u', 'f'])}
set(['y', 'm', 'u', 'd'])
set(['d', 'm'])
{'dummy': set(['d', 'm']), 'funny': set(['y', 'n', 'u', 'f'])}

如您所见,第三行和最后一行不同。为什么在第二种情况下变量“缓存”不同? test -= part(w2) 不像 test = test-part(w2) 吗?

编辑 1 - 感谢您的回答,但为什么 var cache 发生变化?

最佳答案

是的,它们是不同的。比较以下内容:

>>> x = set([1,2,3])
>>> y = x
>>> y -= set([1])
>>> x
set([2, 3])

>>> map(id, (x, y))
[18641904, 18641904]

>>> x = set([1,2,3])
>>> y = x
>>> y = y - set([1])
>>> x
set([1, 2, 3])

>>> map(id, (x, y))
[2774000, 21166000]

换句话说,y -= set(...) 改变了 y。由于 xy 指的是同一个对象,因此它们都发生了变化。

另一方面,y = y - set(...) 创建一个新对象,重新绑定(bind) y 以引用这个新对象。 x 不受影响,因为它仍然指向旧对象。

关于Python "a=a-b"和 "a-=b"真的等价吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15853831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com