How to remove the items in a list that are in a second list in python?

限于喜欢 提交于 2019-12-12 06:46:00

问题


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.


回答1:


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



回答2:



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



来源:https://stackoverflow.com/questions/58842091/how-to-remove-the-items-in-a-list-that-are-in-a-second-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!