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

如何用Python计算集合列表中的共有元素数量?

用Python计算集合列表中的共有元素数量

给定一个包含多个集合的列表,要统计所有集合共有的元素数量,比如示例中的情况:

fav_tv = [{'The Simpsons', 'Modern Family'}, {'Friends', 'The Simpsons'}, {'The Simpsons', 'Friends', 'Seinfeld'}, {'The Simpsons', 'Seinfeld'}]

唯一出现在所有集合里的元素是'The Simpsons',所以输出为1。

方法一:逐次求交集

fav_tv = [{'The Simpsons', 'Modern Family'}, {'Friends', 'The Simpsons'}, {'The Simpsons', 'Friends', 'Seinfeld'}, {'The Simpsons', 'Seinfeld'}]

if not fav_tv:
    output = 0
else:
    common_elements = fav_tv[0].copy()
    for s in fav_tv[1:]:
        common_elements.intersection_update(s)
        if not common_elements:
            break
    output = len(common_elements)

print(output)  # 输出:1
  • 先判断列表是否为空,避免后续操作报错
  • 以第一个集合为初始值,用intersection_update逐个与后续集合求交集(该方法会直接修改原集合,效率更高)
  • 若中途交集为空,提前终止循环节省资源
  • 最后用len()统计共有元素的数量

方法二:简洁的批量交集计算

利用set.intersection()可以接收多个集合参数的特性,直接计算所有集合的交集:

fav_tv = [{'The Simpsons', 'Modern Family'}, {'Friends', 'The Simpsons'}, {'The Simpsons', 'Friends', 'Seinfeld'}, {'The Simpsons', 'Seinfeld'}]

if not fav_tv:
    output = 0
else:
    common_elements = set.intersection(*fav_tv)
    output = len(common_elements)

print(output)  # 输出:1
  • *fav_tv会将列表中的集合拆解为独立参数传入set.intersection()
  • 一行代码就能得到所有集合的交集,写法更简洁直观

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:42:24