Python 从列表中删除空项

Python remove null items from list

我在 python 中为 DynamoBIM 创建了以下列表:

a = [["f", "o", "c"], [null, "o", null], [null, "o", null]]

我想从此列表中删除空项以创建此列表:

a = [["f", "o", "c"], ["o"], ["o"]]

我尝试了 list.remove(x)filters、for-loops 和许多其他方法,但似乎无法摆脱这些问题。

我该怎么做?

假设您的意思是 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']]

您可以使用简单的列表理解:

>>> a = [["f", "o", "c"], [None, "o", null], [null, "o", None]]
>>> a = [[sub for sub in item if sub] for item in a]
>>> a
[['f', 'o', 'c'], ['o'], ['o']]
>>> 

这相当于:

a = [["f", "o", "c"], [None, "o", null], [null, "o", None]]
new = []
for item in a:
    _temp = []
    for sub in item:
        if sub:
            _temp.append(sub)
    new.append(_temp)

a = new

>>> a = [["f", "o", "c"], [None, "o", null], [null, "o", None]]
>>> new = []
>>> for item in a:
...     _temp = []
...     for sub in item:
...         if sub:
...             _temp.append(sub)
...     new.append(_temp)
... 
>>> a = new
>>> a
[['f', 'o', 'c'], ['o'], ['o']]
>>> 
a = [["f", "o", "c"], [None, "o", None], [None, "o", None]]
l = []
for i in a:
    l.append(filter(lambda x: x is not None, i))

print (l)

[['f', 'o', 'c'], ['o'], ['o']]

实际上 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']]

你也可以通过嵌套列表理解来解决:

[[for i in inner_list if i!='null' and not i] for inner_list in list_value]

假设您的意思是 None,您可以尝试使用 filter() 函数:

a = [["f", "o", "c"], [None, "o", None], [None, "o", None]]
print [filter(None,x) for x in a] 

>>> 
[['f', 'o', 'c'], ['o'], ['o']]

"None"和Python中的NaN("not a number")是有区别的,有时习惯上称为"null."NaN的数据类型一般是一个花车。因此,如果您正在处理仅包含字符串的列表,就像这里的情况一样,一个想法是使用列表理解来过滤字符串。

a = ["f", "o", "c", np.nan]
b = [c for c in a if type(c)==str]