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]]
+3
source to share
7 replies
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.
+1
source to share
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]]
+1
source to share