geodude
geodude

Reputation: 231

Smart handling of Python array with many indices

I have the following piece of code:

p1 = np.array([[[[[[[[[[0.]*2]*2]*2]*2]*2]*2]*2]*2]*2]*2)
s = [0]*10
#
# Do something with s
#
p1[s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9]] += 1

Is there a smarter way of:

  1. Creating p1 without all those brackets, and
  2. Access the components of p1 with a string or a list?

I have in mind something like:

p1[s] += 1

or:

p1[*s] += 1

For example, what if instead of 10 indices I wanted N indices?

Upvotes: 1

Views: 54

Answers (1)

Dan D.
Dan D.

Reputation: 74655

np.array([[[[[[[[[[0.]*2]*2]*2]*2]*2]*2]*2]*2]*2]*2)

is better written as:

np.zeros((2,2,2,2,2,2,2,2,2,2))

Or as there are ten 2s:

np.zeros((2,)*10)

Upvotes: 7

Related Questions