使用嵌套索引列表访问列表元素

使用嵌套索引列表访问列表元素

本文介绍了使用嵌套索引列表访问列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何对应于元素[1] [0]和[3] [1]的索引列表(称为"indlst"),例如[[1,0],[3,1,2]]给定列表的[2](称为"lst"),用于访问其各自的元素?例如,给定

How can a list of indices (called "indlst"), such as [[1,0], [3,1,2]] which corresponds to elements [1][0] and [3][1][2] of a given list (called "lst"), be used to access their respective elements? For example, given

    indlst = [[1,0], [3,1,2]]
    lst = ["a", ["b","c"], "d", ["e", ["f", "g", "h"]]]
    (required output) = [lst[1][0],lst[3][1][2]]

输出应对应于["b","h"].我不知道从哪里开始,更不用说找到一种有效的方法了(因为我不认为解析字符串是解决问题的最pythonic方法).

The output should correspond to ["b","h"]. I have no idea where to start, let alone find an efficient way to do it (as I don't think parsing strings is the most pythonic way to go about it).

我应该提到索引的嵌套级别是可变的,因此虽然[1,0]中有两个元素,但[3,1,2]中有三个元素,依此类推. (示例已相应更改).

I should mention that the nested level of the indices is variable, so while [1,0] has two elements in it, [3,1,2] has three, and so forth. (examples changed accordingly).

推荐答案

您可以遍历并收集值.

>>> for i,j in indlst:
...     print(lst[i][j])
...
b
f

或者,您可以使用简单的列表理解从这些值组成一个列表.

Or, you can use a simple list comprehension to form a list from those values.

>>> [lst[i][j] for i,j in indlst]
['b', 'f']



对于可变长度,您可以执行以下操作:

For variable length, you can do the following:

>>> for i in indlst:
...     temp = lst
...     for j in i:
...         temp = temp[j]
...     print(temp)
...
b
h

您可以使用 functions.reduce 列表理解形成一个列表.

You can form a list with functions.reduce and list comprehension.

>>> from functools import reduce
>>> [reduce(lambda temp, x: temp[x], i,lst) for i in indlst]
['b', 'h']

这是python3解决方案.对于python2,您可以忽略import语句.

N.B. this is a python3 solution. For python2, you can just ignore the import statement.

这篇关于使用嵌套索引列表访问列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 13:38