注意到这个奇怪的事情:
>>> a = [3]
>>> a += (1,2)
>>> print(a)
[3, 1, 2]
>>> (1,2) + [3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "list") to tuple
>>> [3] + (1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list
有人可以解释为什么他们的加法如此奇怪吗?-_-
这是列表类型
假设变量是列表类型是合乎逻辑的,那么它将保持列表。
如果加起来会是什么结果
[1, 2] + (3, 4)?元组还是列表?如果相反,首先添加一个元组,然后添加一个列表?为了不欺骗程序员,python 开发人员决定简单地禁止直接添加它们,仅此而已。