简体   繁体   English

Python:如何改变(最后)元组的元素?

[英]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.

相关问题 Python:元组的最后一个元素 - Python: last element of tuple 如何在元组列表中索引元组的最后一个元素 - how to index the last element of a tuple in a list of tuples 如何删除列表中每个元组中的最后一个元素 - How to remove the last element in each tuple in a list 如何在Python中将元组更改为数组? - How to change a tuple into array in Python? 如何更改元组中的第一个元素,它是字典中的键? - How to change the first element in a tuple that is a key in a dictionary? 如何将内部元素元组更改为列表? - how to change the inner element tuple into list? 如何按每个元组中的第一个元素对元组列表进行排序,并选择每个组中最后一个元素最大的元组 - How to sort a list of tuples by the first element in each tuple, and pick the tuple with the largest last element in each group 如何首先相对于元组的第二个元素订购元组列表,然后相对于 python 中的元组的第三个元素订购元组列表? - How to order a list of tuple first with respect to second element of the tuple and then with respenct to third element of the tuple in python? 如何在元组中合并元素或相应地列出python - how to combine element in tuple or list accordingly python 如何在元组中将'issubset'与多个元素一起使用(Python) - how to use 'issubset' with multiple element in tuple (python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM