如果找到多个值中的任何一个,则删除嵌套列表

Remove a nested list if any of multiple values is found

我有一个列表列表,我想删除所有包含多个值的嵌套列表。

list_of_lists = [[1,2], [3,4], [5,6]]
indices = [i for i,val in enumerate(list_of_lists) if (1,6) in val]

print(indices)
[0]

我想要一个满足此条件的索引列表,以便我可以:

del list_of_lists[indices]

删除所有包含特定值的嵌套列表。我猜问题是我尝试检查多个值 (1,6) 因为使用 16 有效。

您可以使用集合操作:

if not {1, 6}.isdisjoint(val)

如果 none 个值出现在另一个序列或集合中,则集合不相交:

>>> {1, 6}.isdisjoint([1, 2])
False
>>> {1, 6}.isdisjoint([3, 4])
True

或者只测试两个值:

if 1 in val or 6 in val

我不会建立索引列表。只需重建列表并在新列表中过滤 out 任何您不想要的内容:

list_of_lists[:] = [val for val in list_of_lists if {1, 6}.isdisjoint(val)]

通过分配给 [:] 整个切片,您可以替换 list_of_lists 中的所有索引,更新列表对象 就地 :

>>> list_of_lists = [[1, 2], [3, 4], [5, 6]]
>>> another_ref = list_of_lists
>>> list_of_lists[:] = [val for val in list_of_lists if {1, 6}.isdisjoint(val)]
>>> list_of_lists
[[3, 4]]
>>> another_ref
[[3, 4]]

请参阅 What is the difference between slice assignment that slices the whole list and direct assignment? 了解有关分配给切片的作用的更多详细信息。