Zeir Zeir - 1 year ago 132
Python Question

How to sum over two indices in python?

Can someone help me out with the

function ?

I am trying to sum over two indices. I want to obtain the following result:

p_t[0, 0]+p_t[0, 1]+p_t[0, 2]+p_t[1, 0]+p_t[1, 1]+p_t[1, 2]+p_t[2,0]+p_t[2, 1]+p_t[2, 2]

, using this code:

sum (p_t[i, j] for i,j in range(num_products))

But I get the error:

TypeError Traceback (most recent call last)
in ()
----> 1 sum (p_t[i, j] for i,j in range(num_products))
in (failed resolving arguments)
TypeError: 'int' object is not iterable

I also tried this but did not work either

sum (p_t[i, j] for i in range(num_products) for j in range(num_products))

Answer Source
sum(p_t[i][j] for i in range(len(p_t)) for j in range(len(p_t[i])))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download