Python - 对元组的元素执行操作

uit*_*400 3 python

我有一个元组(x,y),其中x是一个字符串,y是一个整数.现在,我想执行的操作y,比如y += 1,不希望创建一个新的记录.我怎样才能做到这一点?

Cor*_*mer 6

元组是不可变的,因此您无法直接修改变量

>>> 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
Run Code Online (Sandbox Code Playgroud)

所以你必须分配一个新的元组

>>> t = (t[0], t[1]+1)
>>> t
('foobar', 8)
Run Code Online (Sandbox Code Playgroud)