我有一个这样的清单:
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]]
答案 0 :(得分:1)
您可以使用filter
:
filtered = list(filter(any, a))
答案 1 :(得分:1)
您可以使用:
b = [i for i in a if i.count(None) != len(i)]
答案 2 :(得分:1)
以下内容完全符合您的要求(包括保留任何不是全部None
的子列表,即使您未在示例数据中显示这样的子列表):
a = [[None, None, None],
[None, None, None],
[40.069, 18.642, 1.0],
[41.18, 19.467, 1.0],
[None, None, None],
[42.13, None, 1.5]] # added mixed case
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],
[42.13, 1.5]]
答案 3 :(得分:0)
for lst in a:
if all(x is None for x in lst):
pass
else:
b.append(lst)
答案 4 :(得分:0)
您的子列表似乎是None
值列表或浮点值列表。这意味着您可以使用简单的list comprehension来过滤列表a
,方法是检查每个列表的第一项是否为None
:
>>> 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]]
>>>