【发布时间】:2020-08-10 21:42:10
【问题描述】:
我遇到了这种奇怪的行为,我找不到解释。
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
基本上,当我+= python 不会引发错误并将键附加到列表中时,当我只计算+ 时,我会得到预期的TypeError。
注意:这是 Python 3.6.10
【问题讨论】:
-
见bugs.python.org/issue9314 - “用迭代器连接列表时结果不一致”。另请注意,
+=等在 PEP 中被称为“增强分配”,PEP 203。 -
这有点奇怪
-
我认为@alkasm 的错误链接有一个很好的解释。
When a is mutable, a += b updates it in-place, so there is no ambiguity: the type of a cannot change. When you do a + b, there is no reason to treat a as more deserving than b when selecting the type of the result. -
@ChrisDoyle 这就是确切的推理。这不是“错误”,它是一种防止解释器猜测的机制。
标签: python assignment-operator