python creating new list using a “template list”

4

Suppose i have:

x1 = [1, 3, 2, 4]

and:

x2 = [0, 1, 1, 0]

with the same shape

now i want to "put x2 ontop of x1" and sum up all the numbers of x1 corresponding to the numbers of x2

so the end result is:

end = [1+4 ,3+2]  # end[0] is the sum of all numbers of x1 where a 0 was in x2

this is a naive implementation using list to further clarify the question

store_0 = 0
store_1 = 0
x1 = [1, 3, 4, 2]
x2 = [0, 1, 1, 0]
for value_x1 ,value_x2 in zip(x1 ,x2):
    if value_x2 == 0:
        store_0 += value_x1
    elif value_x2 == 1:
        store_1 += value_x1

so my question: is there is a way to implement this in numpy without using loops or in general just faster?

Share
Improve this question
New contributor
user15770670 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
6
  • 2
    Is it always just a few values? The numpy expression x2==1 returns a set of true/false values that can be used to filter other operations. So, x1[x2==0].sum() and x1[x2==1].sum() do the two operations you have there. – Tim Roberts Apr 26 at 18:59
  • thanks but the solution needs to be ableto handle larger arrays with more values – user15770670 Apr 26 at 19:00
  • Not sure why you didn't take @TimRoberts solution. I just tested with 10,000 element arrays and it took less than a second on my laptop. – Brad Day Apr 26 at 19:11
  • i meant the that the range of the x2 array could have a larger range – user15770670 Apr 26 at 19:13
  • was my fault that i didnt say it – user15770670 Apr 26 at 19:13

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue