2016-12-03 147 views
0

如何将索引列表(称为“indlst”)(如[[1,0],[3,1,2]]与元素[1] [ 0]和[3] [1] [2]给定列表(称为“lst”),用于访问它们各自的元素?例如,给定使用嵌套索引列表访问列表元素

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”]。我不知道从哪里开始,更不用说找到一个有效的方法来做到这一点(因为我不认为解析字符串是最有效的方法)。

EDIT:我应该提到索引的嵌套级别是可变的,所以虽然[1,0]有两个元素,[3,1,2]有三个元素,依此类推。 (例子相应改变)。

+0

我想输出为[“b”,“F”] –

+0

你有一个清单,你有指标,只是参考使用这些列表的元素指数。 –

+0

@Iron困难的部分来自事先不知道有多少索引将引用一个给定的元素。因此,不能像通常那样用i和j引用元素,我不知道需要多少变量。 – amateur3057

回答

1

您可以迭代并收集该值。

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

或者,你可以使用一个简单的列表理解形成列表从这些值。

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

编辑:

对于变长,你可以做到以下几点:

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

可以形成functions.reduce列表理解列表。

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

N.B.这是一个python3解决方案。对于python2,你可以忽略导入语句。

1

你可以试试这个代码块:

required_output = [] 
for i,j in indlst: 
    required_output.append(lst[i][j]) 
1

递归可以抓住从嵌套列表中任意波形/深深索引项目:

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


def nested_lookup(nlst, idexs): 
    if len(idexs) == 1: 
     return nlst[idexs[0]] 
    return nested_lookup(nlst[idexs[0]], idexs[1::]) 

reqout = [nested_lookup(lst, i) for i in indlst] 
print(reqout) 

dindx = [[2], [3, 0], [0], [2], [3, 1, 2], [3, 0], [0], [2]]  
reqout = [nested_lookup(lst, i) for i in dindx] 
print(reqout) 
['b', 'h'] 
['d', 'e', 'a', 'd', 'h', 'e', 'a', 'd'] 

我还发现,任意额外的零个指标都很好:

lst[1][0][0] 
    Out[36]: 'b' 

    lst[3][1][2] 
    Out[37]: 'h' 

    lst[3][1][2][0][0] 
    Out[38]: 'h' 

所以,如果你真的知道最大嵌套深度,你可以通过ov填写索引列表值然后使用.update()方法
将您的(可变数目,更短的)索引列表值写入用零填充的最大固定长度字典中。然后直接硬编码嵌套列表的索引,其忽略任何“额外”硬编码零值指数

低于硬编码4深度:

def fix_depth_nested_lookup(nlst, idexs): 
    reqout = [] 
    for i in idexs: 
     ind = dict.fromkeys(range(4), 0) 
     ind.update(dict(enumerate(i))) 
     reqout.append(nlst[ind[0]][ind[1]][ind[2]][ind[3]]) 
    return reqout 

print(fix_depth_nested_lookup(lst, indlst)) 
['b', 'h']