[英]Python - Perform an operation on an element of a tuple
I have a tuple (x,y)
where x
is a string and y
is an integer. 我有一个元组(x,y)
,其中x
是一个字符串, y
是一个整数。 Now I want to perform an operation on y
, like y += 1
, without wanting to create a new tuple. 现在我想在y
上执行一个操作,比如y += 1
,而不想创建一个新的元组。 How can I do that? 我怎样才能做到这一点?
Tuples are immutable, so you can't directly modify the variable 元组是不可变的,因此您无法直接修改变量
>>> t = ('foobar', 7)
>>> t[1] += 1
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
t[1] += 1
TypeError: 'tuple' object does not support item assignment
So you'd have to assign back a new tuple 所以你必须分配一个新的元组
>>> t = (t[0], t[1]+1)
>>> t
('foobar', 8)
You can't - tuples are immutable. 你不能 - 元组是不可变的。 Any attempt of changing an existing tuple would result in TypeError: 'tuple' object does not support item assignment
. 任何更改现有元组的尝试都会导致TypeError: 'tuple' object does not support item assignment
。
What can be done is re-binding object name to a new tuple based on the previous one. 可以做的是将对象名称重新绑定到基于前一个元组的新元组。
t = ('a', 1)
t = (t[0], t[1]+1)
assert t == ('a', 2)
You can't, since the operation would mutate the tuple, which is not possible. 你不能,因为操作会改变元组,这是不可能的。 Create a new tuple. 创建一个新的元组。
newtuple = (t[0], t[1] + 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.