递归可以抓住从嵌套列表中任意波形/深深索引项目:
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']
我想输出为[“b”,“F”] –
你有一个清单,你有指标,只是参考使用这些列表的元素指数。 –
@Iron困难的部分来自事先不知道有多少索引将引用一个给定的元素。因此,不能像通常那样用i和j引用元素,我不知道需要多少变量。 – amateur3057