Skip to content Skip to sidebar Skip to footer

Dynamic Access Of Multi Dimensional Python Array

I am a python newbie. I was confused on how to access array element dynamically. I have a list b= [1,2,5,8] that I dynamically obtain so its length can vary. With help of this lis

Solution 1:

if the dimensions are [1,2,5,8] you can use numbers 0, 0..1, 0..4, 0..7 for each dimension.

Numpy lets you access positions with tuples:

shape = [1, 2, 5, 8]
pos = [0, 1, 1, 3]

my_array = np.ones(shape)
my_array[tuple(pos)] # will return 1

Solution 2:

You could create a function like:

defarray_update(b, marr, value):
  iflen(b) > 1:
    return array_update(b[1:], marr[b[0]], value)
  marr[b[0]] = value

Given b=[1,2,5,8], to set the value of mArr[1][2][5][8] to foo, you would call:

array_update(b, mArr, 'foo')

Post a Comment for "Dynamic Access Of Multi Dimensional Python Array"