繁体   English   中英

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)filterfor -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", 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']]

实际上Null不在python中,它们应该是字符串,例如

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']]

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

>>> 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']]
>>> 

在Python中,“无”和NaN(“非数字”)之间是有区别的,有时通常被称为“空”。 NaN的数据类型通常是浮点数。 因此,如果您只处理一个字符串列表(如此处所示),则一种想法是使用列表推导来过滤字符串。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM