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

如何高效编写Python代码找出三个集合的公共元素?

高效获取多个集合的公共元素

你当前用三重嵌套循环找公共元素的方式效率极低——时间复杂度是O(len(s1)*len(s2)*len(s3)),集合元素越多,性能下降越明显。Python的集合本身基于哈希表实现,内置了专门的交集操作,效率要高得多。

推荐两种更高效的实现方式:

方式一:使用&运算符

&是集合交集的运算符,支持多个集合连续计算:

s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {3, 4, 5}
common = s1 & s2 & s3
for elem in common:
    print(elem)

方式二:使用intersection()方法

intersection()可以直接接收多个集合作为参数,结果和&完全一致:

s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {3, 4, 5}
common = s1.intersection(s2, s3)
for elem in common:
    print(elem)

如果你的集合数量不固定(比如存在一个列表里),可以用解包的方式批量计算:

all_sets = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}]
common = set.intersection(*all_sets)
for elem in common:
    print(elem)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:25:24