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

Python中如何判断两个列表是否存在共同元素

Python判断两个列表是否存在共同元素的实现方案

方法1:优先推荐(性能最优,适合绝大多数场景)

利用集合的isdisjoint()方法判断,该方法会在匹配到第一个共同元素后提前终止遍历,不需要处理全部元素,时间复杂度为O(min(len(list1), len(list2))):

list1 = [1, 2, 3, 4]
list2 = [4, 5, 6, 7]

# 存在共同元素时返回True,否则返回False
has_common_element = not set(list1).isdisjoint(list2)
print(has_common_element) # 示例输出:True

如果需要同时获取所有共同元素,直接求集合交集即可:

common_elements = set(list1).intersection(list2)
# 等价写法:common_elements = set(list1) & set(list2)
print(common_elements) # 示例输出:{4}

方法2:适配含不可哈希元素的场景

如果列表中包含不可哈希的元素(比如嵌套列表、字典等),无法转为集合时可以用遍历判断:

has_common_element = any(item in list2 for item in list1)

注意事项

  • 元素量级较大时优先使用集合方案,性能远高于遍历判断
  • 如果列表允许有重复元素,集合运算会自动去重,需要保留重复共同元素的话可以单独写遍历逻辑统计

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:45:03