Python - 多个列表的交集
在本文中,我们将了解如何以不同的方式求多个列表的交集。让我们从传统的方式开始。
遵循以下步骤解决问题
- 初始化两个包含多个列表的列表
- 遍历第一个列表,并在当前项目在第二个列表中也存在时,将其添加到新列表中。
- 打印结果。
示例
# initializing the lists list_1 = [[1, 2], [3, 4], [5, 6]] list_2 = [[3, 4]] # finding the common items from both lists result = [sub_list for sub_list in list_1 if sub_list in list_2] # printing the result print(result)
如果您运行以上代码,则可以得到以下结果。
输出
[[3, 4]]
我们使用集合来求两个列表的交集。遵循以下步骤。
- 使用 map 将两个列表项转换为元组。
- 使用交集和 map 方法求两个集合的交集。
- 将结果转换为列表
- 打印结果。
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
示例
# initializing the lists list_1 = [[1, 2], [3, 4], [5, 6]] list_2 = [[3, 4]] # converting each sub list to tuple for set support tuple_1 = map(tuple, list_1) tuple_2 = map(tuple, list_2) # itersection result = list(map(list, set(tuple_1).intersection(tuple_2))) # printing the result print(result)
如果您运行以上代码,则可以得到以下结果。
输出
[[3, 4]]
结论
如果您对本文有任何疑问,请在评论部分注明。
广告