[英]How can I remove None elements from list of lists
我有一个这样的清单:
a = [[None, None, None],
[None, None, None],
[40.069, 18.642, 1.0],
[41.18, 19.467, 1.0],
[None, None, None]]
我希望它是这样的。 做这个的最好方式是什么? 谢谢
b = [[40.069, 18.642, 1.0], [41.18, 19.467, 1.0]]
以下内容完全符合您所说的要求(包括保留并非全部为None
任何子列表,即使您没有在示例数据中显示这样的子列表):
a = [[None, None, None],
[None, None, None],
[40.069, 18.642, 1.0],
[41.18, 19.467, 1.0],
[None, None, None],
[0, 0, 0], # added all int zeros
[0.0, 0.0, 0.0], # added all float zeros
[42.13, None, 1.5]] # added mixture
b = []
for sublist in a:
cleaned = [elem for elem in sublist if elem is not None]
if len(cleaned): # anything left?
b.append(cleaned)
print(b)
输出:
[[40.069, 18.642, 1.0],
[41.18, 19.467, 1.0],
[0, 0, 0],
[0.0, 0.0, 0.0],
[42.13, 1.5]]
如果你有 Python 3.8+,你可以非常简洁地使用赋值表达式以及这样的列表理解:
b = [cleaned for sublist in a
if (cleaned := [elem for elem in sublist if elem is not None])]
您可以使用filter
:
filtered = list(filter(any, a))
你可以使用这个:
b = [i for i in a if i.count(None) != len(i)]
for lst in a:
if all(x is None for x in lst):
pass
else:
b.append(lst)
看起来您的子列表将是None
值列表或浮点值列表。 这意味着您可以使用简单的列表推导式通过检查每个列表的第一项是否为None
来过滤列表a
:
>>> a = [[None, None, None],
... [None, None, None],
... [40.069, 18.642, 1.0],
... [41.18, 19.467, 1.0],
... [None, None, None]]
>>> b = [x for x in a if x[0] is not None]
>>> b
[[40.069, 18.642, 1.0], [41.18, 19.467, 1.0]]
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.