【问题标题】:remove an arbitrary element from a nest of lists and dicts in python从python中的列表和字典的嵌套中删除任意元素
【发布时间】:2016-04-22 21:07:41
【问题描述】:
a = [ 
    {
        'b':[1,2,3]
    },{
        'c':{
            'd':'e',
            'f':'g'
        }
    } 
]
b = [0,'b',2]
c = [2,'c','f']

在上面,我想使用bc中包含的键来销毁a中的对应元素。在这种情况下,del a[1]['b'][2] 对应于a,或者a[2]['c'].pop('f') 对应于c

在给定任意深度和树结构的情况下,是否有一种干净的方法来做到这一点?

【问题讨论】:

    标签: python list dictionary nested


    【解决方案1】:
    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)
    

    【讨论】:

    • 感谢您的快速帮助。我认为这仅适用于列表,不适用于字典。您的代码在第一个循环中在 structure = structure[item] 上返回“KeyError b”,我也不确定 del 是否适用于字典。
    • 错误原因是因为b应该是[0,'b',2]。我刚刚对此进行了测试,del 确实适用于字典。
    • 摇滚吧,斯凯勒。非常感谢。做到了。
    • 很高兴它有帮助!玩得开心编码:)
    猜你喜欢
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    相关资源
    最近更新 更多