Reputation: 313
I'm new to python.. My question: I have a list rt, and a list with indices rtInd, which varies in size and content.
For all the indices in rtInd, I want to change the corresponding elements in rt.
Example: 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
Upvotes: 0
Views: 1244
Reputation: 155333
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):
# 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).
That said, numpy
is a pretty heavyweight dependency; if you're not already relying on numpy
, I'd stick to the simple loop described in M Z's answer.
Upvotes: 0
Reputation: 4799
If you have a list of indices, and you have x
, you can loop through and update the values at the corresponding indices:
rt = [10,20,30,40]
rtInd = [2,3]
x = 10
for i in rtInd:
rt[i] += x
# result:
# rt = [10, 20, 40, 50]
Upvotes: 1