我是 python 的新手。我的问题:我有一个列表 rt 和一个带有索引 rtInd 的列表,它的大小和内容各不相同。
对于rtInd中的所有索引,我想改变rt中对应的元素。
示例:rt = [10,20,30,40]; rtInd = [2,3]
我想要的:
rt[2] = 30 + x
rt[3] = 40 + x
有人可以帮我吗?
提前致谢!
艾米
答案 0 :(得分:1)
如果您有一个索引列表,并且您有 x
,您可以遍历并更新相应索引处的值:
rt = [10,20,30,40]
rtInd = [2,3]
x = 10
for i in rtInd:
rt[i] += x
# result:
# rt = [10, 20, 40, 50]
答案 1 :(得分:0)
如果 rt
是 numpy
数组,您可以使用索引本身的 list
(或 numpy.array
)进行索引(必须不是一个 tuple
,要清楚,因为 tuple
用于多维访问,而不是一组要修改的索引):
# Setup
rt = numpy.array([10, 20, 30, 40], dtype=np.int64)
rtInd = [2, 3] # Or numpy.array([2, 3])
x = 123 # Arbitrary value picked
# Actual work
rt[rtInd] += x
这会将工作推送到 numpy
内的单个操作(可能会提高性能)。
也就是说,numpy
是一个非常重量级的依赖项;如果您还没有依赖 numpy
,我会坚持使用 M Z's answer 中描述的简单循环。