I created the following list in python for 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.
How can I do this?
Assuming you mean None
by null, you can use a list comprehension:
>>> 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 = 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
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]
Assuming you meant None
, you could try using the filter()
function:
a = [["f", "o", "c"], [None, "o", None], [None, "o", None]]
print [filter(None,x) for x in a]
>>>
[['f', 'o', 'c'], ['o'], ['o']]
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." The data type of NaN is generally a float. 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.