I have a list of lists, and another list, and I want to remove all of the items from the list of lists that are in the second list.
first = [[1,3,2,4],[1,2],[3,4,2,5,1]]
to_remove = [1,2]
How would I go about doing this problem in general?
There are also similar questions on here but nothing has helped.
result = []
for l in first:
tmp = []
for e in l:
if e not in to_remove:
tmp.append(e)
result.append(tmp)
print(result)
This code loop over all the list and all the element of each list if the element is in to_remove list it skip it and go to the next. so if you have multiple intance it will remove it
Best regard
An elegant solution using sets
:
first = [[1,3,2,4],[1,2],[3,4,2,5,1]]
to_remove = [1,2]
result = [list(set(x).difference(to_remove)) for x in first]
result
[[3, 4], [], [3, 4, 5]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.