Passing a list as an index to assign values in an n-dimensional nested list

时间:2019-02-24 00:24:23

标签: python list recursion multidimensional-array

I will have nested arrays of arbitrary dimension represented as lists (not numpy arrays). For instance, this is a example mylist of dimension 4x3x2:

  [[[0, 0], [0, 0], [0, 0]],
   [[0, 0], [0, 0], [0, 0]],
   [[0, 0], [0, 0], [0, 0]],
   [[0, 0], [0, 0], [0, 0]]]

Now, given a list represending an index, how would I set the corresponding index of this list (with a length equal to the number of dimensions in mylist) at value? For instance, if [2, 0, 1] is passed to the function, how would I turn mylist into

  [[[0, 0], [0, 0], [0, 0]],
   [[0, 0], [0, 0], [0, 0]],
   [[0, X], [0, 0], [0, 0]],
   [[0, 0], [0, 0], [0, 0]]]

I tried incrementally setting a pointer (not sure if this is the right term) variable to achieve this, e.g. res= mylist; res = res[2]; ...; res[1] = X but this doesn't produce expected results. Importantly, the exact dimension of mylist isn't known in advance, so it just as well could have been a 4x3x2x8 array.

1 个答案:

答案 0 :(得分:1)

Getter

这是一个在列表中输入参数然后在索引中输入参数的函数。

def accessor(array: list, *indexes: int):
    return array if not len(indexes) else accessor(array[indexes[0]], *indexes[1:])

用法

print(mylist[2][0][1] is accessor(mylist, 2, 0, 1))
  


设置器

要能够编辑值,这里还有另一个功能。首先是列表,然后是您要放置的值以及哪个索引系列。

def replacor(array: list, value, *indexes: int):
    accessor(array, *indexes[:-1])[indexes[-1]] = value

用法

mylist = [0, 0, [[0, 0]]]
replacor(mylist, "hi !", 2, 0, 1)
print(mylist)
  

[0,0,[[0,'hi!']]]