Cle*_*ter 20 python assignment-operator
我遇到了这种奇怪的行为,我找不到解释。
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
mak*_*kis 17
l += ...实际上是在可变时调用object.__iadd__(self, other)和修改对象in-placel
原因(正如@DeepSpace 在他的评论中所解释的)是,当您执行l += {'a': 2}操作时l,仅更新就地并且仅当l是可变的。另一方面,操作l + {'a': 2}没有就地完成,导致list + dictionary -> TypeError.
(见这里)
l = [1]
l = l.__iadd__({'a': 2})
l
#[1, 'a']
Run Code Online (Sandbox Code Playgroud)
和+那个叫不一样object.__add__(self, other)
l + {'B': 3}
Run Code Online (Sandbox Code Playgroud)
TypeError: can only concatenate list (not "dict") to list
Run Code Online (Sandbox Code Playgroud)