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)
或者,您可以使用numpy并构建要递增的值列表,然后简单地将它们添加到一起,例如:
如果您有大元组,并且只想在某些索引处递增,而不需要手动索引:
正如Jon评论的那样,如果有多个索引,可以使用一组要递增的索引:
我倾向于使用^{} ,而使用^{} method :
这也为元组中的各个元素提供了语义意义,即您引用的是
bar
,而不仅仅是第1
个元素。你知道吗相关问题 更多 >
编程相关推荐