通过列表索引嵌套列表 [英] Indexing nested list by a list
本文介绍了通过列表索引嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出了类似的嵌套列表
>>> m= [[3, 1], [2, 7]]
我可以得到这样的元素
>>> m[1][0]
2
如果在列表中给出索引,即 [1,0]
,如何获得相同的值?
How can i get the same value if the index is given in a list, i.e. as [1, 0]
?
我正在寻找Q编程语言通过 dot 像下面的代码一样
I am looking for something that the Q programming language offers with dot like in code below
q) m: (3 1; 2 7)
q) m[1][0]
2
q) m . 1 0
2
推荐答案
作为快速解决问题的方法,您可以像这样滥用 functools.reduce
:
As a quick-n-dirty solution, you can abuse functools.reduce
like this:
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
有很多特殊情况需要处理(此外,您必须确保路径存在或处理出现的任何错误),但这应该可以帮助您入门.
There are quite a few corner cases to handle (plus you'd have to be sure the path exists or else handle any errors that arise) but this should get you started.
这篇关于通过列表索引嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文