[英]Python - change multiple elements in list based on indices
I'm new to python.. My question: I have a list rt, and a list with indices rtInd, which varies in size and content.我是 python 的新手。我的问题:我有一个列表 rt 和一个带有索引 rtInd 的列表,它的大小和内容各不相同。
For all the indices in rtInd, I want to change the corresponding elements in rt.对于 rtInd 中的所有索引,我想更改 rt 中的相应元素。
Example: rt = [10,20,30,40]; rtInd = [2,3]
示例:
rt = [10,20,30,40]; rtInd = [2,3]
rt = [10,20,30,40]; rtInd = [2,3]
What I want:我想要的是:
rt[2] = 30 + x
rt[3] = 40 + x
Can someone help me?有人能帮我吗?
Thanks in advance!提前致谢!
Amy艾米
If you have a list of indices, and you have x
, you can loop through and update the values at the corresponding indices:如果您有一个索引列表,并且您有
x
,则可以循环并更新相应索引处的值:
rt = [10,20,30,40]
rtInd = [2,3]
x = 10
for i in rtInd:
rt[i] += x
# result:
# rt = [10, 20, 40, 50]
If rt
is a numpy
array, you could index with the list
(or numpy.array
) of indices itself (must not be a tuple
, to be clear, due to tuple
s being used for multidimensional access, not a set of indices to modify):如果
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
and that will push the work to a single operation inside numpy
(potentially improving performance).这会将工作推向
numpy
内的单个操作(可能会提高性能)。
That said, numpy
is a pretty heavyweight dependency;也就是说,
numpy
是一个相当重量级的依赖; if you're not already relying on numpy
, I'd stick to the simple loop described in MZ's answer .如果您还没有依赖
numpy
,我会坚持使用MZ 的回答中描述的简单循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.