0

Given two lists (a and b), I'd like to replace three elements of list 'a' with three elements of list 'b'. Currently I am using an expression like this:

a[0], a[5], a[7] = b[11], b[99], b[2]

As I need to do such operations very frequently with lots of different arrays I am wondering if there is a more compact solution for this problem (the number of elements I need to replace is always 3 though). I was thinking about something like:

a[0,5,7] = b[11,99,2]

Which obviously does not work.

2 Answers 2

2

If you've a python list you can do something like this :

toReplace = [0,5,7]
targetIndices = [11, 99, 2]

for i,j in zip(toReplace, targetIndices): a[i] = b[j]

If you've a numpy array, it's even simpler :

a[toReplace] = b[targetIndices]
#i.e, a[[0,5,7]] = b[[11, 99, 2]]
Sign up to request clarification or add additional context in comments.

2 Comments

This simplifies the code when you need to replace fair amount of elements, but not when you need to replace only a couple of them. I have specified my question more, I always need to replace three element at a given time.
@Istvanb if you've a python list, then that's all you can do, just in case you've a numpy array you can do something like you want to do, see the updated answer.
1

There might be some better solutions but this does the trick:

ind1 = [0,5,7] 
ind2 = [11,99,2]

for i in range(len(ind1)):
    a[ind1[i]]=b[ind2[i]]

1 Comment

This simplifies the code when you need to replace fair amount of elements, but not when you need to replace only a couple of them. I have specified my question more, I always need to replace three element at a given time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.