Python:在给定索引列表的情况下访问多维列表的元素 [英] Python: Accessing elements of multi-dimensional list, given a list of indexes

查看:351
本文介绍了Python:在给定索引列表的情况下访问多维列表的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维列表F,其中包含某种类型的元素.因此,例如,如果等级为4,则可以通过F[a][b][c][d]之类的东西访问F的元素.

I have a multidimensional list F, holding elements of some type. So, if for example the rank is 4, then the elements of F can be accessed by something like F[a][b][c][d].

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

Given a list L=[a,b,c,d], I would like to access F[a][b][c][d]. My problem is that my rank is going to be changing, so I cannot just have F[L[0]][L[1]][L[2]][L[3]].

理想情况下,我希望能够执行F[L]并获取元素F[a][b][c][d].我认为可以使用numpy来完成类似的操作,但是对于我正在使用的数组类型,numpy不适合,所以我想使用python列表来做到这一点.

Ideally, I would like to be able to do F[L] and get the element F[a][b][c][d]. I think something like this can be done with numpy, but for the types of arrays that I'm using, numpy is not suitable, so I want to do it with python lists.

如何获得上述类似内容?

How can I have something like the above?

有关我要实现的目标的具体示例,请参阅Martijn的答案中的演示.

For a specific example of what I'm trying to achieve, see the demo in Martijn's answer.

推荐答案

您可以使用

You can use the reduce() function to access consecutive elements:

from functools import reduce  # forward compatibility
import operator

reduce(operator.getitem, indices, somelist)

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

In Python 3 reduce was moved to the functools module, but in Python 2.6 and up you can always access it in that location.

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

The above uses the operator.getitem() function to apply each index to the previous result (starting at somelist).

演示:

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

这篇关于Python:在给定索引列表的情况下访问多维列表的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆