创建 Python 元组的略微修改的副本?
Create a slightly modified copy of a Python tuple?
我有一个 Python 元组,t
,有 5 个条目。 t[2]
是一个 int
。如何创建另一个内容相同但 t[2]
递增的元组?
有没有更好的方法:
t2 = (t[0], t[1], t[2] + 1, t[3], t[4]) ?
我倾向于使用 namedtuple
instead, and use the _replace
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
个元素。
如果您有大元组并且只想在某些索引处递增而不手动索引:
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))
或者,您可以使用 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)
使用元组切片,构建新的元组:
t2 = t[:2] + (t[2] + 1,) + t[3:]
我有一个 Python 元组,t
,有 5 个条目。 t[2]
是一个 int
。如何创建另一个内容相同但 t[2]
递增的元组?
有没有更好的方法:
t2 = (t[0], t[1], t[2] + 1, t[3], t[4]) ?
我倾向于使用 namedtuple
instead, and use the _replace
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
个元素。
如果您有大元组并且只想在某些索引处递增而不手动索引:
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))
或者,您可以使用 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)
使用元组切片,构建新的元组:
t2 = t[:2] + (t[2] + 1,) + t[3:]