假设我们有 2 个列表,一个是嵌套列表,例如:
a = [[[['test'],['test1']], ['test2']], ['test3', 'test4']]
另一个存储索引:
b = [0,1,0]
所以我们可以检索 test2
:
a[0][1][0]
我想知道有没有什么方便的方法可以根据 index 列表从嵌套列表中检索值?
答案 0 :(得分:3)
这样的事情怎么样:
a = [[[["test"], ["test1"]], ["test2"]], ["test3", "test4"]]
b = [0, 1, 0]
item = a
for i in b:
item = item[i]
print(item) # test2
答案 1 :(得分:0)
这听起来像是一些函数式编程和 reduce 方法的完美用例:
lambda
嵌套列表用作reduce函数的初始值设定项,然后在索引数组上逐层减少直到找到结果。当用作reduce 下一次迭代的输入时,reduce 使用的内部{{1}} 函数获取下一个索引并在该嵌套级别拉出数组。