Bla*_*ake 1 python null list filter
我在python中创建了以下列表DynamoBIM:
a = [["f", "o", "c"], [null, "o", null], [null, "o", null]]
Run Code Online (Sandbox Code Playgroud)
我想从此列表中删除空项以创建此列表:
a = [["f", "o", "c"], ["o"], ["o"]]
Run Code Online (Sandbox Code Playgroud)
我尝试过list.remove(x),filters,for-loops和其他一些方法,但似乎无法摆脱这些错误.
我怎样才能做到这一点?
假设你的意思None是null,你可以使用列表理解:
>>> null = None
>>> nested_list = [["f", "o", "c"], [null, "o", null], [null, "o", null]]
>>> [[x for x in y if x] for y in nested_list]
[['f', 'o', 'c'], ['o'], ['o']]
Run Code Online (Sandbox Code Playgroud)
如果null是某个其他值,您可以更改上面的值以将其设置为其他值,null并将理解更改为:
>>> null = None # Replace with your other value
>>> [[x for x in y if x != null] for y in nested_list]
[['f', 'o', 'c'], ['o'], ['o']]
Run Code Online (Sandbox Code Playgroud)
小智 2
实际上Python中没有Null,它们应该是字符串
list_value = [["f", "o", "c"], ['null', "o", 'null'], ['null', "o", 'null']]
[filter(lambda x: x!='null' and x!=None, inner_list) for inner_list in list_value]
[['f', 'o', 'c'], ['o'], ['o']]
Run Code Online (Sandbox Code Playgroud)
您还可以通过嵌套列表理解来解决:
[[for i in inner_list if i!='null' and not i] for inner_list in list_value]
Run Code Online (Sandbox Code Playgroud)