从嵌套列表中删除空子列表
Removing empty sublists from a nested list
我有以下嵌套列表:
mynestedlist = [[[], [], [], ['Foo'], [], []], [[], ['Bar'], [], []], ['FOO'], 'BAR']
我想将它展平到最外面的项目,这样主列表中就有 4 个项目。但是,我只想要带有文本的项目并且想要删除空的括号列表。
期望的输出:
mynestedlist = [[['Bar']], ['FOO'], 'BAR']
我尝试了以下方法:
newlist = []
for i in mynestedlist:
for sub in i:
if sub != []:
newlist.append(sub)
但是,我得到以下输出:
[['Foo'], ['bar'], 'FOO', 'B', 'A', 'R']
您混合使用了列表和字符串,它们都是可迭代的。您需要在此处显式测试列表,然后递归或使用堆栈:
def clean_nested(l):
cleaned = []
for v in l:
if isinstance(v, list):
v = clean_nested(v)
if not v:
continue
cleaned.append(v)
return cleaned
演示:
>>> mynestedlist = [[[], [], [], ['Foo'], [], []], [[], ['Bar'], [], []], ['FOO'], 'BAR']
>>> clean_nested(mynestedlist)
[[['Foo']], [['Bar']], ['FOO'], 'BAR']
请注意,如果空列表中有空列表,此解决方案会删除除最外层列表以外的所有列表:
>>> nested_empty = [[[],[],[],[],[],[]],[[],['Bar'],[], []], ['FOO'], 'BAR']
>>> clean_nested(nested_empty)
[[['Bar']], ['FOO'], 'BAR']
>>> all_nested_empty = [[[],[],[],[],[],[]],[[],[],[], []], []]
>>> clean_nested(all_nested_empty)
[]
执行以下操作:
def del_empty(lst):
if isinstance(lst, list):
return [del_empty(sub) for sub in lst if sub != []]
return lst
>>> del_empty(mynestedlist)
[[['Foo']], [['Bar']], ['FOO'], 'BAR']
通过一些递归,可以在保留字符串元素的同时删除任意深度的空列表。
def remove_nested_null(a):
if not isinstance(a, list):
return a
a = map(remove_nested_null, a)
a = list(filter(None, a))
return a
我有以下嵌套列表:
mynestedlist = [[[], [], [], ['Foo'], [], []], [[], ['Bar'], [], []], ['FOO'], 'BAR']
我想将它展平到最外面的项目,这样主列表中就有 4 个项目。但是,我只想要带有文本的项目并且想要删除空的括号列表。
期望的输出:
mynestedlist = [[['Bar']], ['FOO'], 'BAR']
我尝试了以下方法:
newlist = []
for i in mynestedlist:
for sub in i:
if sub != []:
newlist.append(sub)
但是,我得到以下输出:
[['Foo'], ['bar'], 'FOO', 'B', 'A', 'R']
您混合使用了列表和字符串,它们都是可迭代的。您需要在此处显式测试列表,然后递归或使用堆栈:
def clean_nested(l):
cleaned = []
for v in l:
if isinstance(v, list):
v = clean_nested(v)
if not v:
continue
cleaned.append(v)
return cleaned
演示:
>>> mynestedlist = [[[], [], [], ['Foo'], [], []], [[], ['Bar'], [], []], ['FOO'], 'BAR']
>>> clean_nested(mynestedlist)
[[['Foo']], [['Bar']], ['FOO'], 'BAR']
请注意,如果空列表中有空列表,此解决方案会删除除最外层列表以外的所有列表:
>>> nested_empty = [[[],[],[],[],[],[]],[[],['Bar'],[], []], ['FOO'], 'BAR']
>>> clean_nested(nested_empty)
[[['Bar']], ['FOO'], 'BAR']
>>> all_nested_empty = [[[],[],[],[],[],[]],[[],[],[], []], []]
>>> clean_nested(all_nested_empty)
[]
执行以下操作:
def del_empty(lst):
if isinstance(lst, list):
return [del_empty(sub) for sub in lst if sub != []]
return lst
>>> del_empty(mynestedlist)
[[['Foo']], [['Bar']], ['FOO'], 'BAR']
通过一些递归,可以在保留字符串元素的同时删除任意深度的空列表。
def remove_nested_null(a):
if not isinstance(a, list):
return a
a = map(remove_nested_null, a)
a = list(filter(None, a))
return a