0

有没有一种简单的方法可以从列表中删除每个空列表、字典、键,如下所示:

[1, 2, [], 0, {                                                                                                                                 
'a': 'b',                                                               
'c': '',                                                                  
'd': {                                                                   
    '1': []                                                             
     }                                                                   
}, [                                                                      
    1, [                                                                  
        2, [                                                              
            [], []                                                       
           ]                                                             
       ]                                                                  
    ]                                                                     
]

并得到这样的列表:

[1, 2, 0, {                                                                  
'a': 'b',                                                              
}, [                                                                  
    1, [                                                                
        2,                                                                                                                                       
       ]                                                              
    ]                                                                  
]

?

4

1 回答 1

0

我写了我的解决方案:

import numbers

def strip_empty_structs(struct):
    def keep(v):
        return isinstance(v, numbers.Number) or v

    if type(struct) == list:
        struct = [strip_empty_structs(s) for s in struct]
        struct = filter(keep, struct)
    if type(struct) == dict:
        for k, v in struct.iteritems():
            struct[k] = strip_empty_structs(v)
        struct = dict(
            (
                (k, v) for k, v in struct.iteritems()
                if keep(v)
            )
        )

    return struct
于 2013-04-18T08:53:52.947 回答