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将两个列表项转换为元组。
使用相交和映射方法相交两个集合。
将结果转换为列表
打印结果。
示例
# 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]]
结论
如果您对本文有任何疑问,请在评论部分中提及它们。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短