[英]How to return all item in list of lists that are not in other list of lists in Python?
I have 2 list of lists:我有 2 个列表:
list1: [[1,2,3],[2,5],[6,7,4]]
list2: [[1,3],[2],[6,4],[9,0,3]]
I want to do few things:我想做几件事:
Find every number that is in list 1 but is not in list 2, store it in a new list, and then append this new list to list2.查找列表 1 中但不在列表 2 中的每个数字,将其存储在新列表中,然后将此新列表附加到列表 2。 In our case:
new_list = [5,7]
and then, we will add it to list2 = [[1,3],[2],[6,4],[9,0,3],[5,7]]
在我们的例子中:
new_list = [5,7]
然后,我们将它添加到list2 = [[1,3],[2],[6,4],[9,0,3],[5,7]]
Then, I want to remove duplicates of numbers from each list1 and list 2:然后,我想从每个 list1 和 list 2 中删除重复的数字:
In our case: list1 = [[1,3],[2,5],[6,7,4]], list2 = [[1],[2],[6,4],[9,0,3],[5,7]]
在我们的例子中:
list1 = [[1,3],[2,5],[6,7,4]], list2 = [[1],[2],[6,4],[9,0,3],[5,7]]
I have an implementation using For loops, but I need something more elegant for that.我有一个使用 For 循环的实现,但我需要一些更优雅的东西。 Can you help me please find out a way?
你能帮我找出一个方法吗?
使用 Python,您可以使用集合推导来完成第一部分:
list2.append(list({i for j in list1 for i in j}.difference({i for j in list2 for i in j})))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.