a = [
{
'b':[1,2,3]
},{
'c':{
'd':'e',
'f':'g'
}
}
]
b = [0,'b',2]
c = [2,'c','f']
在上文中,我想使用b
或c
中包含的键来销毁a
中的相应元素。在这种情况下,del a[1]['b'][2]
为a
,a[2]['c'].pop('f')
为c
。
在给定任意深度和树结构的情况下,是否有一种干净的方法可以做到这一点?
答案 0 :(得分:2)
def nested_del(structure, del_spec):
for item in del_spec[:-1]: # Loop through all but the last element.
structure = structure[item] # Go further into the nested structure
del structure[del_spec[-1]] # Use the last element to delete the desired value
nested_del(a, b)
nested_del(a, c)