📜  Python|两个嵌套列表的交集

📅  最后修改于: 2022-05-13 01:54:49.059000             🧑  作者: Mango

Python|两个嵌套列表的交集

这篇特别的文章旨在实现两个列表相交的任务,其中每个元素本身就是一个列表。这也是一个有用的实用程序,因为如果程序员处于开发世界中,这种任务可能会出现在程序员的生活中。让我们讨论一些实现此任务的方法。

方法1:朴素方法
这是完成此任务的最简单方法,并使用执行循环的蛮力方法并检查一个列表是否包含与另一个列表相似的列表。

# Python 3 code to demonstrate 
# find intersection of nested list
# using naive method
  
# initializing lists
test_list1 = [ [1, 2], [3, 4], [5, 6] ]
test_list2 = [ [3, 4], [5, 7], [1, 2] ]
  
# printing both lists 
print ("The original list 1 : " + str(test_list1))
print ("The original list 2 : " + str(test_list2))
  
# using naive method 
# to get list intersection
res_list = []
for i in test_list1:
    if i in test_list2:
        res_list.append(i)
  
# printing the intersection 
print ("The intersection of two lists is : " + str(res_list))

输出 :

The original list 1 : [[1, 2], [3, 4], [5, 6]]
The original list 2 : [[3, 4], [5, 7], [1, 2]]
The intersection of two lists is : [[1, 2], [3, 4]]

方法 2:使用列表推导
我们可以在相对较少的情况下执行与上述类似的任务。的行。但是该方法与上面类似,只是使用列表理解方法来执行任务。

# Python 3 code to demonstrate 
# find intersection of nested list
# using list comprehension
  
# initializing lists
test_list1 = [ [1, 2], [3, 4], [5, 6] ]
test_list2 = [ [3, 4], [5, 7], [1, 2] ]
  
# printing both lists 
print ("The original list 1 : " + str(test_list1))
print ("The original list 2 : " + str(test_list2))
  
# using list comprehension
# to get list intersection
res_list = [i for i in test_list1 if i in test_list2]
  
# printing the intersection 
print ("The intersection of two lists is : " + str(res_list))

输出 :

The original list 1 : [[1, 2], [3, 4], [5, 6]]
The original list 2 : [[3, 4], [5, 7], [1, 2]]
The intersection of two lists is : [[1, 2], [3, 4]]

方法 3:使用set() + map()&
执行此任务的最有效和推荐的方法是使用set()map()的组合来实现它。首先使用 map 将内部列表转换为元组,并设置外部列表,使用 &运算符可以执行集合交集,从而执行此任务。此外,如果需要以列表方式获取列表,我们可以使用map()将外部容器和内部容器转换回列表。

# Python 3 code to demonstrate 
# find intersection of nested list
# using map() + set() + &
  
# initializing lists
test_list1 = [ [1, 2], [3, 4], [5, 6] ]
test_list2 = [ [3, 4], [5, 7], [1, 2] ]
  
# printing both lists 
print ("The original list 1 : " + str(test_list1))
print ("The original list 2 : " + str(test_list2))
  
# using map() + set() + &
# to get list intersection
res_set = set(map(tuple, test_list1)) & set(map(tuple, test_list2))
res_list = list(map(list, res_set))
  
# printing the intersection 
print ("The intersection of two lists is : " + str(res_list))

输出 :

The original list 1 : [[1, 2], [3, 4], [5, 6]]
The original list 2 : [[3, 4], [5, 7], [1, 2]]
The intersection of two lists is : [[1, 2], [3, 4]]