You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何实现多列表两两交集的合并?是否有内置函数?

解决多个列表两两交集合并的问题

Python没有直接完成这个需求的单一内置函数,但可以用标准库工具组合实现,具体步骤和代码如下:

实现思路

  1. 先将所有列表转为集合,便于高效计算交集
  2. 用itertools.combinations生成所有不重复的列表两两组合
  3. 对每组组合计算交集,最后合并所有交集结果

代码示例

分步实现版本

import itertools

arr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
# 把列表批量转成集合
set_list = list(map(set, arr))
# 生成所有两两集合的组合
pair_combinations = itertools.combinations(set_list, 2)
# 初始化结果集合
final_result = set()

# 遍历每组组合,计算交集并合并到结果中
for set_a, set_b in pair_combinations:
    final_result.update(set_a & set_b)

print(final_result)  # 输出: {2, 3, 4}

简洁一行版

import itertools

arr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
final_result = set().union(*(a & b for a, b in itertools.combinations(map(set, arr), 2)))
print(final_result)  # 输出: {2, 3, 4}

关键代码解释

  • itertools.combinations(set_list, 2):生成所有不重复的两两集合对,比如示例中会生成({1,2,3}, {2,3,4})、({1,2,3}, {3,4,5})、({2,3,4}, {3,4,5})三组
  • set_a & set_b:等价于set.intersection(set_a, set_b),快速计算两个集合的交集
  • set().union(...):将所有交集结果合并为一个集合,自动完成去重

内容的提问来源于stack exchange,提问作者Anmol Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 17:35:25