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

如何在Kotlin中实现多个List的交集运算

多列表求交集的解决方案

如果你用的是Python,可以借助functools.reduce实现多列表的交集计算——它能把交集操作反复应用在所有列表上,逐步缩小结果范围,完美解决单个intersect函数无法处理多参数的问题。

方法一:用reduce配合集合操作

  1. 把所有筛选得到的列表放到一个大列表中
  2. 通过reduce依次对每个列表执行交集运算

示例代码:

from functools import reduce

# 假设这是你筛选出的5个列表
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
list3 = [2, 3, 5]
list4 = [3, 5, 8]
list5 = [3, 5]

all_lists = [list1, list2, list3, list4, list5]
# 计算所有列表的交集,最后转回列表格式
result = list(reduce(lambda a, b: set(a) & set(b), all_lists))
print(result)  # 输出 [3, 5]

方法二:手动迭代计算

不想用reduce的话,也可以手动循环实现:

# 初始交集设为第一个列表的集合
current_intersection = set(list1)

# 依次和后续每个列表取交集
for lst in all_lists[1:]:
    current_intersection &= set(lst)
    # 交集为空时提前终止,提升效率
    if not current_intersection:
        break

result = list(current_intersection)

额外提示

  • 如果列表包含重复元素,转集合会自动去重;若需要保留重复次数,得统计每个元素在所有列表中的出现次数,取最小值来生成结果
  • 若某个筛选后的列表为空,直接返回空列表即可,无需继续计算

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:15:48