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


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

+3


source


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]]

      

+2


source


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


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

!

+1


source


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]]

      

+1


source


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


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

+1


source







All Articles