是否有一种简单的方法可以从列表中删除每个空列表,字典,键,如下所示:
[1, 2, [], 0, {
'a': 'b',
'c': '',
'd': {
'1': []
}
}, [
1, [
2, [
[], []
]
]
]
]
并获取如下列表:
[1, 2, 0, {
'a': 'b',
}, [
1, [
2,
]
]
]
答案 0 :(得分: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