Python removes a sublist in a list if a specific item is inside that subnet
for example
list_of_specific_element = [2,13]
list = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]
I want the sublist including any value inside the list of a specific item to be removed from the list.
Therefore the item [2,1],[2,3],[13,12],[13,14]
must be removed from the list.
the final list of results should be[[1,0],[15,13]]
listy=[elem for elem in listy if (elem[0] not in list_of_specific_element) and (elem[1] not in list_of_specific_element)]
Using a single user interface to compile a list
You can use many intersections:
>>> exclude = {2, 13}
>>> lst = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]
>>> [sublist for sublist in lst if not exclude.intersection(sublist)]
[[1, 0]]
You can write:
list_of_specific_element = [2,13] set_of_specific_element = set(list_of_specific_element) mylist = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]] output = [ item for item in mylist if not set_of_specific_element.intersection(set(item)) ]
which gives:
>>> output
[[1, 0]]
It uses sets, sets intersection and list comprehension.
Simple list-only solution:
list = [x for x in list if all(e not in list_of_specific_element for e in x)]
And you really shouldn't be calling him list
!
Filter and lambda version
list_of_specific_element = [2,13] list = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]] filtered = filter(lambda item: item[0] not in list_of_specific_element, list) print(filtered) >>> [[1, 0], [15, 13]]
You can use list comprehension
and any()
to do a trick like this example:
list_of_specific_element = [2,13]
# PS: Avoid calling your list a 'list' variable
# You can call it somthing else.
my_list = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]
final = [k for k in my_list if not any(j in list_of_specific_element for j in k)]
print(final)
Output:
[[1, 0]]
I think you can use:
match = [2,13]
lst = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]
[[lst.remove(subl) for m in match if m in subl]for subl in lst[:]]
demo