Python: 如何使用字符串索引 ( '[0][1][0]' ) 作为多维数组的索引

Python: How to use a String Index ( '[0][1][0]' ) as the Index for a multidimensional Array

我想使用字符串:'[0][1][0]' 作为多维数组的索引。如果我编写代码 myarray[0][1][0],我会从第一项的第一个 Child 和第二个 Child ( [0][1][0]).

中获取内容

仍然有效:

myarray = [
            [
              'child 0',
              [
                'child 0,0',
                [
                  'child 0,0,0'
                ]
                'child 0,1',
                [
                  'child 0,1,0'
                ]
              ]
            ],
            [
              'child 1',
              [
                'child 1,0',
                'child 1,1'
              ],
            [
              'child 2',
              [
                'child 2,0'
              ]
            ]
          ]
print myarray[0][1][0] # >> prints: "child 0,1,0"

这肯定行不通:

# use same array as above (myarray)
sindex='[0][1][0]'
print myarray[sindex] # should print: "child 0,1,0" but results in "KeyError: '[0][1][0]'"

编辑:

从下面的评论中了解到(谢谢大家!)重要的是要知道 sindex 的长度可以像 '[1][0][2]''[2][1][4][2][0]' 一样变化。

编辑二:

据我所知,改变 Brian 的 解决方案并不容易

def get_index_from_string(arr, idx_string):
    i = [int(i) for i in idx_string[1:-1].split('][')]
    res = arr[:]
    for x in i:
        res = res[x]
    return res

为了能够使用 myarray[0][1].pop(0) 从数组中删除项目,他只是吐出节点值而不是指向它。一个解决方案可能是通过对它进行迭代来重建数组,但这是不可能的,因为它继承了多种不同的类型,我必须解析然后在没有节点 Brian 的函数 find 的情况下完全重建一个副本。

还有 Leon 的 解决方案

from functools import reduce
import operator
reduce(operator.getitem, sindex, myarray)

我不知道如何将 Reduce 转换为 pop() 解决方案。

这看起来绝对像是一个 XY 问题:索引最初是如何最终成为一个字符串的?在我看来,您可以用更好的方式存储这些信息。

肯定没有内置函数来解析表示索引的字符串。我建议首先从字符串中解析出索引,然后照常进行。

对于二维列表,这可能如下所示:

>>> my_array = [[1, 2], [3, 4]]
>>> sindex = '[1][0]'
>>> y, x = [int(i) for i in sindex[1:-1].split('][')]
>>> my_array[y][x]
3

或者,您可以使用 eval,但是 eval is evil,所以我不会告诉您如何操作。

编辑:

如果您需要可以处理可变长度的函数,请尝试以下操作。 (同样,实际问题可能出在上游。)这个函数非常难看,复制了原始数组:

>>> def get_index_from_string(arr, idx_string):
...     i = [int(i) for i in idx_string[1:-1].split('][')]
...     res = arr[:]
...     for x in i:
...         res = res[x]
...     return res
...
>>> my_arr = [1, 2, 3]
>>> my_arr2 = [[1,2],[3,4]]
>>> my_arr3 = [[[1,2],[3,4]],[[5,6],[7,8]]]
>>> get_index_from_string(my_arr, '[1]')
2
>>> get_index_from_string(my_arr2, '[1][0]')
3
>>> get_index_from_string(my_arr3, '[1][0][1]')
6