2013-04-11 65 views
0

值有一個簡單的方法來從列表中刪除所有的空列表,字典,關鍵是這樣的:深刪除空列表,並從

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

並獲得名單如下:

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

+1

什麼是你真的* *意欲何爲? – 2013-04-11 06:35:06

回答

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