1

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 list I need to update multi-dimensional array as mArr[1] [2] [5] [8] . The length of the list and array dimension matches as given in the example

Basically, I am looking a technique to access a multi dimensional array with respect to the list "b" as in the form of : marr[b]. This m-array is also dynamically created.

I tried looking on to tutorials of numpy but was not figure out the solution.Am I missing something?

Thanks in advance.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

8 Comments

no need to do that reshape thing. Just pass the shape as parameter to np.ones
tx for the quick reply..can you elaborate it more..i am confused in third line...what if, if I have b=[3,4,7,8,10,20] next time, how to access my array as myarr[3][4][7][8][10][20]....
@iinception, the third line creates an array, only the fourth line is concerned with accessing.
tx all...tuple was the keyword I was looking forr.. :)
@iinception, now I understood. [1,2,5,8] is not the dimension, so you just use b = (1,2,5,8) and myarr[b] or myarr[tuple(b)] if b is a list
|
1

You could create a function like:

def array_update(b, marr, value):
  if len(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')

Comments

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.