Python“a = a-b”和“a- = b”真的相同吗?
发布时间:2020-12-20 12:22:01 所属栏目:Python 来源:网络整理
导读:似乎a = a-b与a = = b不同,我不知道为什么. 码: cache = {}def part(word): if word in cache: return cache[word] else: uniq = set(word) cache[word] = uniq return uniqw1 = "dummy"w2 = "funny"# workstest = part(w1)print(test)test = test-part(w2)
似乎a = a-b与a = = 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','d']),'funny': set(['y','n','f'])} set(['y','d']) set(['d','m']) {'dummy': set(['d','m']),'f'])} 如您所见,第三行和最后一行不同.为什么在第二种情况下变量“缓存”是不同的? test – = part(w2)不像test = test-part(w2)? 编辑1 – 感谢您的答案,但为什么var缓存更改? 解决方法
是的,他们是不同的.比较以下内容:
>>> x = set([1,2,3]) >>> y = x >>> y -= set([1]) >>> x set([2,3]) >>> map(id,(x,y)) [18641904,18641904] 同 >>> x = set([1,3]) >>> y = x >>> y = y - set([1]) >>> x set([1,y)) [2774000,21166000] 换句话说,y – = set(…)会在适当的位置改变y.由于x和y都指向同一个对象,因此它们都会发生变化. 另一方面,y = y – set(…)创建一个新对象,重新绑定y以引用这个新对象. x不受影响,因为它仍然指向旧对象. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |