我在 python 中为 DynamoBIM 创建了以下列表:
a = [["f", "o", "c"], [null, "o", null], [null, "o", null]]
我想从此列表中删除空项以创建此列表:
a = [["f", "o", "c"], ["o"], ["o"]]
我尝试过 list.remove(x)、filter、for 循环和许多其他方法,但无法似乎摆脱了这些错误。
我该怎么做?
请您参考如下方法:
假设你的意思是 null None,你可以使用列表理解:
>>> 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']]
如果 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']]
