在Python中从嵌套的列表和字典中删除任意元素

3
a = [ 
    {
        'b':[1,2,3]
    },{
        'c':{
            'd':'e',
            'f':'g'
        }
    } 
]
b = [0,'b',2]
c = [2,'c','f']

在上述代码中,我希望使用bc中包含的键来删除a中对应的元素。在这种情况下,对于a,可以使用del a[1]['b'][2],对于c,可以使用a[2]['c'].pop('f')
是否有一种简洁的方式可以在树结构中任意深度地实现这一操作?
1个回答

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)

感谢您的快速帮助。我认为这仅适用于列表,而不是字典。您的代码在第一次循环时返回“KeyError b”于structure = structure[item],而且我也不确定del是否适用于字典。 - Adam
错误的原因是因为 b 应该是 [0,'b',2]。我刚测试了一下,del 在字典上确实可以使用。 - skyler
太棒了,Skyler。非常感谢。就是这样。 - Adam
很高兴能帮到你!祝你编程愉快 :) - skyler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接