python - Remove a nested list if any of multiple values is found -
i have list of lists , i'd remove nested lists contain of multiple values.
list_of_lists = [[1,2], [3,4], [5,6]] indices = [i i,val in enumerate(list_of_lists) if (1,6) in val] print(indices) [0]
i'd lists of indices conditions can:
del list_of_lists[indices]
to remove nested lists contain values. i'm guessing problem try check against multiple values (1,6)
using either 1
or 6
works.
you use set operation:
if not {1, 6}.isdisjoint(val)
a set disjoint if none of values appear in other sequence or set:
>>> {1, 6}.isdisjoint([1, 2]) false >>> {1, 6}.isdisjoint([3, 4]) true
or test both values:
if 1 in val or 6 in val
i'd not build list of indices. rebuild list , filter out don't want in new list:
list_of_lists[:] = [val val in list_of_lists if {1, 6}.isdisjoint(val)]
by assigning [:]
whole slice replace indices in list_of_lists
, updating list object in-place:
>>> list_of_lists = [[1, 2], [3, 4], [5, 6]] >>> another_ref = list_of_lists >>> list_of_lists[:] = [val val in list_of_lists if {1, 6}.isdisjoint(val)] >>> list_of_lists [[3, 4]] >>> another_ref [[3, 4]]
see what difference between slice assignment slices whole list , direct assignment? more detail on assigning slice does.
Comments
Post a Comment