[英]Python: how to change (last) element of tuple?
The question is a bit misleading, because a tuple is immutable . 这个问题有点误导,因为元组是不可变的 。 What I want is: 我想要的是:
Having a tuple a = (1, 2, 3, 4)
get a tuple b
that is exactly like a
except for the last argument which is, say, twice the last element of a
. 具有元组a = (1, 2, 3, 4)
得到的元组b
是酷似a
除了最后一个参数是,比方说,两倍的最后一个元素a
。
=> b == (1, 2, 3, 8) => b ==(1,2,3,8)
b = a[:-1] + (a[-1]*2,)
What I'm doing here is concatenation of two tuples, the first containing everything but the last element, and a new tuple containing the mutation of the final element. 我在这里做的是连接两个元组,第一个包含除最后一个元素之外的所有元素,以及包含最终元素变异的新元组。 The result is a new tuple containing what you want. 结果是一个包含你想要的新元组。
Note that for +
to return a tuple, both operands must be a tuple. 注意,对于+
来返回一个元组,两个操作数必须是一个元组。
I would do something like: 我会做的事情如下:
b=list(a)
b[-1]*=2
b=tuple(b)
Here's one way of doing it: 这是一种方法:
>>> a = (1, 2, 3, 4)
>>> b = a[:-1] + (a[-1]*2, )
>>> a
(1, 2, 3, 4)
>>> b
(1, 2, 3, 8)
So what happens on the second line? 那么第二行会发生什么? a[:-1] means all of a except the last element. a [: - 1]表示除最后一个元素之外的所有a。 a[-1] is the last element, and we multiply it by two. a [-1]是最后一个元素,我们将它乘以2。 The (a[-1]*2, ) turns the result into a tuple, and the sliced tuple is concatenated with it using the + operator. (a [-1] * 2,)将结果转换为元组,并使用+运算符将切片的元组与其连接。 The result is put in b. 结果放在b中。
You can probably fit this to your specific case. 你可能适合你的具体情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.