通过列表索引嵌套列表

时间:2018-07-28 20:39:00

标签: python multidimensional-array indexing nested-lists

给出了类似的嵌套列表

>>> m= [[3, 1], [2, 7]]

我可以得到这样的元素

>>> m[1][0]
2

如果在列表中给出索引,即[1, 0],如何获得相同的值?

我正在寻找Q编程语言通过dot提供的功能,例如下面的代码

q) m: (3 1; 2 7)
q) m[1][0]
2
q) m . 1 0
2

4 个答案:

答案 0 :(得分:4)

作为一种快速的解决方案,您可以像这样滥用 functools.reduce

from functools import reduce
def get_recursive(lst, idx_list):
    return reduce(list.__getitem__, [lst, *idx_list])

>>> y = [[3, 1], [2, 7]]
>>> get_recursive(y, [0, 1])
1
>>> get_recursive(y, [1, 0])
2

有很多特殊情况需要处理(此外,您必须确保路径存在或处理出现的任何错误),但这应该可以帮助您入门。

答案 1 :(得分:1)

仅定义一个递归函数,该函数将获取传递列表的索引,然后将该索引和切片索引列表传递给自身,直到切片索引列表为空:

def get(m,l):
    if not l:
        return m
    return get(m[l[0]],l[1:])

print(get([[3, 1], [2, 7]],[1,0]))

打印:2

答案 2 :(得分:1)

此解决方案需要导入,但只能从标准库中导入。与 @cs95's solution 非常相似,但在我看来更简洁。

from functools import reduce
from operator import getitem

nested_list = [[[['test'], ['test1']], ['test2']], ['test3', 'test4']]
indices = [0, 1, 0]

assert reduce(getitem, indices, nested_list) == 'test2'

答案 3 :(得分:0)

您可以先转换为NumPy数组:

import numpy as np

m = [[3, 1], [2, 7]]
np.array(m)[1,0]

输出:

2