创建一个稍微修改过的Python元组副本?

2024-04-26 07:22:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python元组t,有5个条目。t[2]是一个int。如何创建另一个具有相同内容但t[2]递增的元组?你知道吗

有没有比以下更好的方法:

t2 = (t[0], t[1], t[2] + 1, t[3], t[4]) ?

Tags: 方法内容条目int元组t2
3条回答

或者,您可以使用numpy并构建要递增的值列表,然后简单地将它们添加到一起,例如:

In [6]: import numpy as np

# your tuple
In [7]: t1 = (1, 2, 3, 4, 5)

# your list of values you want to increment
# this acts as a mask for mapping your values
In [8]: n = [0, 0, 1, 0, 0]

# add them together and numpy will only increment the respective position value
In [9]: np.array(t1) + n
Out[9]: array([1, 2, 4, 4, 5])

# convert back to tuple
In [10]: tuple(np.array(t1) + n)                                            
Out[11]: (1, 2, 4, 4, 5)

如果您有大元组,并且只想在某些索引处递增,而不需要手动索引:

tuple(e + 1 if i == 2 else e for i, e in enumerate(t))

正如Jon评论的那样,如果有多个索引,可以使用一组要递增的索引:

 tuple(e + 1 if i in {1,3} else e for i, e in enumerate(t))

我倾向于使用^{},而使用^{} method

>>> from collections import namedtuple
>>> Test = namedtuple('Test', 'foo bar baz')
>>> t1 = Test(1, 2, 3)
>>> t1
Test(foo=1, bar=2, baz=3)
>>> t2 = t1._replace(bar=t1.bar+1)
>>> t2
Test(foo=1, bar=3, baz=3)

这也为元组中的各个元素提供了语义意义,即您引用的是bar,而不仅仅是第1个元素。你知道吗

相关问题 更多 >