Python:给定索引列表,访问多维列表的元素

geo*_*909 2 python list

我有一个多维列表F,持有某种类型的元素.因此,如果例如等级为4,则可以通过类似的方式访问F的元素F[a][b][c][d].

给出一个列表L=[a,b,c,d],我想访问F[a][b][c][d].我的问题是我的排名会发生变化,所以我不能只是F[L[0]][L[1]][L[2]][L[3]].

理想情况下,我希望能够做到F[L]并获得元素F[a][b][c][d].我觉得这样的事情可以用numpy完成,但对于我正在使用的数组类型,numpy不适合,所以我想用python列表来做.

我怎么能有类似上面的东西?

编辑:有关我想要实现的具体示例,请参阅Martijn答案中的演示.

Mar*_*ers 10

您可以使用该reduce()函数访问连续元素:

from functools import reduce  # forward compatibility
import operator

reduce(operator.getitem, indices, somelist)
Run Code Online (Sandbox Code Playgroud)

在Python 3 reduce中移动到functools模块,但在Python 2.6及更高版本中,您始终可以在该位置访问它.

以上使用operator.getitem()函数将每个索引应用于前一个结果(从开始somelist).

演示:

>>> import operator
>>> somelist = ['index0', ['index10', 'index11', ['index120', 'index121', ['index1220']]]]
>>> indices = [1, 2, 2, 0]
>>> reduce(operator.getitem, indices, somelist)
'index1220'
Run Code Online (Sandbox Code Playgroud)