使用存储在另一个列表中的索引访问列表中的元素 [英] Access element in list using indexes stored in another list
本文介绍了使用存储在另一个列表中的索引访问列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种使用存储在另一个列表中的索引访问列表中元素的通用方法.
I'm looking for a general way to access elements in a list using indexes stored in another list.
例如,我有以下列表:
b = [[[[[0.2], [3]], [[4.5], [78]], [[1.3], [0.23]], [[6.], [9.15]]],
[[[3.1], [44]], [[1.], [66]], [[0.18], [2.3]], [[10], [7.5]]],
[[[3], [4.]], [[12.3], [12]], [[7.8], [3.7]], [[1.2], [2.1]]]]]
我需要访问其索引存储在以下元素中:
and I need to access the element whose index are stored in:
c = [0, 0, 0, 1, 0]
即:
3
这行不通:
b[c[0]][c[1]][c[2]][c[3]][c[4]]
因为b
的形状随代码的每次运行而变化,所以这就是为什么我需要一种 general 方式来使用c
来访问b
中的元素的原因.
because the shape of b
changes with every run of my code, which is why I need a general way of using c
to access the element in b
.
类似的东西:
b[*c]
我敢打赌会奏效,但那没有.
that I would've bet would work, but it doesn't.
推荐答案
使用减少(或 functools.reduce 用于向前兼容使用Python 3)
Use reduce (or functools.reduce for forward-compatible with Python 3)
>>> def getitems(data, keys):
... return reduce(lambda a, b: a[b], [data]+keys)
...
>>> getitems(b, c)
3
这假定keys
始终是列表.
这篇关于使用存储在另一个列表中的索引访问列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文