栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Python中有效地知道两个列表的交集是否为空

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Python中有效地知道两个列表的交集是否为空

或更简洁

if set(L) & set(M):    # there is an intersectionelse:    # no intersection

如果您确实需要

True
False

bool(set(L) & set(M))

经过一段时间后,这似乎也是尝试的好选择

m_set=set(M)any(x in m_set  for x in L)

如果M或L中的项目不可散列,则必须使用效率较低的方法,例如

any(x in M for x in L)

以下是100个商品列表的一些时间安排。在没有交集的情况下,使用集合的速度要快得多,在有交集的情况下,使用集合的速度要慢一些。

M=range(100)L=range(100,200)timeit set(L) & set(M)10000 loops, best of 3: 32.3 µs per looptimeit any(x in M for x in L)1000 loops, best of 3: 374 µs per looptimeit m_set=frozenset(M);any(x in m_set  for x in L)10000 loops, best of 3: 31 µs per loopL=range(50,150)timeit set(L) & set(M)10000 loops, best of 3: 18 µs per looptimeit any(x in M for x in L)100000 loops, best of 3: 4.88 µs per looptimeit m_set=frozenset(M);any(x in m_set  for x in L)100000 loops, best of 3: 9.39 µs per loop# Now for some random listsimport randomL=[random.randrange(200000) for x in xrange(1000)]M=[random.randrange(200000) for x in xrange(1000)]timeit set(L) & set(M)1000 loops, best of 3: 420 µs per looptimeit any(x in M for x in L)10 loops, best of 3: 21.2 ms per looptimeit m_set=set(M);any(x in m_set  for x in L)1000 loops, best of 3: 168 µs per looptimeit m_set=frozenset(M);any(x in m_set  for x in L)1000 loops, best of 3: 371 µs per loop


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/653101.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号