为什么 Python 元组中列表的 += 会引发 TypeError 但无论如何都要修改列表? [英] Why does += of a list within a Python tuple raise TypeError but modify the list anyway?
问题描述
我刚刚遇到了一些很奇怪的事情.
<预><代码>>>>t = ([],)>>>t[0].append('你好')>>>吨(['你好'],)>>>t[0] += ['世界']回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:元组"对象不支持项目分配>>>吨(['你好,世界'],)为什么它会引发 TypeError
而改变 tuple
中的 list
?
正如我在评论中开始提到的,+=
实际上修改了列表 就地 然后尝试将结果分配给元组中的第一个位置.来自数据模型文档:
调用这些方法来实现增广算术赋值(+=, -=, =,/=,//=, %=, *=, <<=, >>=, &=, ^=, |=).这些方法应该尝试就地执行操作(修改 self)并返回结果(可能是但不一定是 self).
+=
因此等价于:
t[0].extend(['world']);t[0] = t[0];
所以就地修改列表不是问题(1. step),因为列表是可变的,但是将结果分配回元组是无效的(2. step),这就是抛出错误的地方.
I just came across something that was quite strange.
>>> t = ([],)
>>> t[0].append('hello')
>>> t
(['hello'],)
>>> t[0] += ['world']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t
(['hello', 'world'],)
Why does it raise TypeError
and yet change the list
inside the tuple
?
As I started mentioning in comment, +=
actually modifies the list in-place and then tries to assign the result to the first position in the tuple. From the data model documentation:
These methods are called to implement the augmented arithmetic assignments (+=, -=, =, /=, //=, %=, *=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).
+=
is therefore equivalent to:
t[0].extend(['world']);
t[0] = t[0];
So modifying the list in-place is not problem (1. step), since lists are mutable, but assigning the result back to the tuple is not valid (2. step), and that's where the error is thrown.
这篇关于为什么 Python 元组中列表的 += 会引发 TypeError 但无论如何都要修改列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!