[英]Search a list of Item Lists and return all elements of list with Python
[英]How to return all item in list of lists that are not in other list of lists in Python?
我有 2 个列表:
list1: [[1,2,3],[2,5],[6,7,4]]
list2: [[1,3],[2],[6,4],[9,0,3]]
我想做几件事:
查找列表 1 中但不在列表 2 中的每个数字,将其存储在新列表中,然后将此新列表附加到列表 2。 在我们的例子中: new_list = [5,7]
然后,我们将它添加到list2 = [[1,3],[2],[6,4],[9,0,3],[5,7]]
然后,我想从每个 list1 和 list 2 中删除重复的数字:
在我们的例子中: list1 = [[1,3],[2,5],[6,7,4]], list2 = [[1],[2],[6,4],[9,0,3],[5,7]]
我有一个使用 For 循环的实现,但我需要一些更优雅的东西。 你能帮我找出一个方法吗?
使用 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.