[英]Python remove null items from list
I created the following list in python for DynamoBIM
: 我在python中为DynamoBIM
创建了以下列表:
a = [["f", "o", "c"], [null, "o", null], [null, "o", null]]
I want to remove the null items from this list to create this list: 我想从此列表中删除空项目以创建此列表:
a = [["f", "o", "c"], ["o"], ["o"]]
I've attempted list.remove(x)
, filter
s, for
-loops, and a number of other methods but cannot seem to get rid of these buggers. 我尝试了list.remove(x)
, filter
, for
-loops和许多其他方法,但似乎无法摆脱这些漏洞。
How can I do this? 我怎样才能做到这一点?
Assuming you mean None
by null, you can use a list comprehension: 假设您用空表示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']]
In case null is some other value, you can alter the above to set the value of null
as that something else, and alter the comprehension to: 如果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']]
Actually Null is not in python, their it should be string like 实际上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']]
You could also solve by nested list comprehension: 您还可以通过嵌套列表理解来解决:
[[for i in inner_list if i!='null' and not i] for inner_list in list_value]
You can use a simple list comprehension: 您可以使用简单的列表理解:
>>> 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']]
>>>
This is equivalent to: 这等效于:
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']]
>>>
There is a difference between "None" and NaN ("not a number") in Python, which is sometimes conventionally referred to as "null." 在Python中,“无”和NaN(“非数字”)之间是有区别的,有时通常被称为“空”。 The data type of NaN is generally a float. NaN的数据类型通常是浮点数。 Therefore, if you are working with a list of only strings, as seems to be the case here, one idea is to filter for strings using a list comprehension. 因此,如果您只处理一个字符串列表(如此处所示),则一种想法是使用列表推导来过滤字符串。
a = ["f", "o", "c", np.nan]
b = [c for c in a if type(c)==str]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.