Skip to main content
 首页 » 编程设计

python之获取两个列表列表或空列表的交集

2025年05月04日8artech

我有两个形状相同的列表列表。

list1 = [[1,2,3], [], [4,5], []] 
list2 = [[1,2], [7], [4,5], []] 

我需要这个列表列表:

[[1,2], [], [4,5], []] 

我怎样才能得到它?

P.S.:这些主题对我没有帮助:

Python - Intersection of two lists of lists

Find intersection of two nested lists?

请您参考如下方法:

假设 list1 和 list2 中的每个列表只包含不同的元素,并且您不关心输出中元素的顺序,您可以使用 set 交集来帮助你:

output = [list(set(l1) & set(l2)) for l1, l2 in zip(list1, list2)]