我是靠谱客的博主 深情海燕,最近开发中收集的这篇文章主要介绍python多维列表索引,Python:在给定索引列表的情况下访问多维列表的元素,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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].

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]].

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?

EDIT: 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)

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.

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

Demo:

>>> import operator

>>> somelist = ['index0', ['index10', 'index11', ['index120', 'index121', ['index1220']]]]

>>> indices = [1, 2, 2, 0]

>>> reduce(operator.getitem, indices, somelist)

'index1220'

最后

以上就是深情海燕为你收集整理的python多维列表索引,Python:在给定索引列表的情况下访问多维列表的元素的全部内容,希望文章能够帮你解决python多维列表索引,Python:在给定索引列表的情况下访问多维列表的元素所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(39)

评论列表共有 0 条评论

立即
投稿
返回
顶部