Skip to main content
 首页 » 编程设计

python 列表作为嵌套列表的索引

2025年05月04日22del

我有以下两个列表:

l1 = [2, 3, 2] 
l2 = [0, [0, 1], [0, 1, 0, [0, 1, [0, 0]]]] 

我如何使用第一个列表作为树索引,以便将一个项目 append 到第二个列表,就像做

l2[2][3][2].append(0)  

请您参考如下方法:

没有标准的方法可以做到这一点,但这会起作用:

from functools import reduce 
from operator import getitem 
 
def tree_index(tree, index): 
    return reduce(getitem, index, tree) 
 
tree_index(l2, l1).append(0) 

作为奖励,tree_index 函数也适用于字典和任何其他映射。例如:

>>> adjs = {'apple': ['red', 'green'], 'swallow': ['african', 'european'] } 
>>> tree_index(adjs, ['apples', 0]) 
'red' 

另一方面,tree_index 不适用于赋值。这是行不通的:

tree_index(l2, [1,1]) = 33 # throws SyntaxError 

为了分配给树索引,您需要另一个函数或部分索引:

tree_index(l2, [1])[1] = 33