我今天发现了一件奇怪的事情,并想知道是否有人可以了解这里的差异是什么?
import numpy as np
A = np.arange(12).reshape(4,3)
for a in A:
a = a + 1
B = np.arange(12).reshape(4,3)
for b in B:
b += 1
Run Code Online (Sandbox Code Playgroud)
运行每个for
循环后,A
没有更改,但B
已经添加了一个元素.我实际上使用该B
版本写入for
循环内的初始化NumPy数组.
+=
python中的运算符似乎在列表上意外运行.谁能告诉我这里发生了什么?
class foo:
bar = []
def __init__(self,x):
self.bar += [x]
class foo2:
bar = []
def __init__(self,x):
self.bar = self.bar + [x]
f = foo(1)
g = foo(2)
print f.bar
print g.bar
f.bar += [3]
print f.bar
print g.bar
f.bar = f.bar + [4]
print f.bar
print g.bar
f = foo2(1)
g = foo2(2)
print f.bar
print g.bar
Run Code Online (Sandbox Code Playgroud)
OUTPUT
[1, 2]
[1, 2]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3]
[1]
[2] …
Run Code Online (Sandbox Code Playgroud) 一个代码块有效,但另一个代码没有.哪个是有意义的,除了第二个块与第一个块相同,只是用速记写的操作.它们实际上是相同的操作.
l = ['table']
i = []
Run Code Online (Sandbox Code Playgroud)
for n in l:
i += n
print(i)
Run Code Online (Sandbox Code Playgroud)
输出: ['t', 'a', 'b', 'l', 'e']
for n in l:
i = i + n
print(i)
Run Code Online (Sandbox Code Playgroud)
输出:
TypeError:只能将列表(不是"str")连接到列表
是什么导致了这个奇怪的错误?
a = [1, 2, 3]
a[-1] += a.pop()
Run Code Online (Sandbox Code Playgroud)
这导致了[1, 6]
.
a = [1, 2, 3]
a[0] += a.pop()
Run Code Online (Sandbox Code Playgroud)
这导致了[4, 2]
.什么评估顺序给出了这两个结果?
我遇到了这种奇怪的行为,我找不到解释。
MWE:
l = [1]
l += {'a': 2}
l
[1, 'a']
l + {'B': 3}
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: can only concatenate list (not "dict") to list
Run Code Online (Sandbox Code Playgroud)
基本上,当我+=
python 不会引发错误并将密钥附加到列表时,而当我只计算时,+
我得到了预期的TypeError
.
注意:这是 Python 3.6.10
为什么以下抛出异常,虽然它成功了?
>>> t = ([1, 2, 3], 4)
>>> t[0] += [1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t
([1, 2, 3, 1], 4)
>>>
Run Code Online (Sandbox Code Playgroud) 在Python中,写作x = x+1
和x += 1
?之间是否有任何区别(语义,效率等)?
我理解在python中的每一件事,无论是数字,字符串,字典还是任何东西都是一个对象.变量名只是指向内存中的对象.现在根据这个问题,
>> a_dict = b_dict = c_dict = {}
这将创建一个空字典,并且所有变量都指向此dict对象.因此,改变任何一个都会反映在其他变量中.
>> a_dict["key"] = "value" #say
>> print a_dict
>> print b_dict
>> print c_dict
Run Code Online (Sandbox Code Playgroud)
会给
{'key': value}
{'key': value}
{'key': value}
Run Code Online (Sandbox Code Playgroud)
我已经理解了指向对象的变量的概念,所以这看起来很公平.
现在即使它可能很奇怪,因为它是如此基本的陈述,为什么会发生这种情况?
>> a = b = c = 1
>> a += 1
>> print a, b, c
2, 1, 1 # and not 2, 2, 2
Run Code Online (Sandbox Code Playgroud)
问题的第一部分:为什么这里应用的概念不同?
实际上,当我试图为此寻找解决方案时,出现了这种疑问:
>> a_dict = {}
>> some_var = "old_value"
>> a_dict['key'] = some_var
>> some_var = "new_value" …
Run Code Online (Sandbox Code Playgroud) 我注意到在尝试p= p+i
不同的列表时, p += i
例如:
test = [0, 1, 2, 3,]
p = test
test1 = [8]
p = p + test1
print test
Run Code Online (Sandbox Code Playgroud)
在上面的代码中test
打印出原始值[0, 1, 2, 3,]
但是如果我在下面p = p + test1
用p += test1
As 切换
test = [0, 1, 2, 3,]
p = test
test1 = [8]
p += test1
print test
Run Code Online (Sandbox Code Playgroud)
test
现在等于 [0, 1, 2, 3, 8]
价值不同的原因是什么?