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

标签 python list performance intersection

假设我有两个列表,L 和 M。现在我想知道它们是否共享一个元素。 如果他们共享一个元素,哪一种是询问(在 python 中)的最快方法? 我不在乎他们共享哪些元素,或者有多少,只要他们是否共享。

例如,在这种情况下

L = [1,2,3,4,5,6]
M = [8,9,10]

我应该得到 False,这里:

L = [1,2,3,4,5,6]
M = [5,6,7]

我应该得到 True。

我希望问题很清楚。 谢谢!

曼努埃尔

最佳答案

或者更简洁

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

如果你真的需要 TrueFalse

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 loop

timeit any(x in M for x in L)
1000 loops, best of 3: 374 µs per loop

timeit m_set=frozenset(M);any(x in m_set  for x in L)
10000 loops, best of 3: 31 µs per loop

L=range(50,150)

timeit set(L) & set(M)
10000 loops, best of 3: 18 µs per loop

timeit any(x in M for x in L)
100000 loops, best of 3: 4.88 µs per loop

timeit 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 lists
import random
L=[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 loop

timeit any(x in M for x in L)
10 loops, best of 3: 21.2 ms per loop

timeit m_set=set(M);any(x in m_set  for x in L)
1000 loops, best of 3: 168 µs per loop

timeit m_set=frozenset(M);any(x in m_set  for x in L)
1000 loops, best of 3: 371 µs per loop

关于python - 在python中有效地知道两个列表的交集是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2197482/

相关文章:

python - 使用python从opencv级联获取特定的图像横截面

python - 在 Plotly 气泡图中标记特定气泡

python - 如何通过循环将字典列表的列表转换为数据框

c++ - 列表、指针和局部变量

performance - OpenGL - 一次将所有数据传递到着色器时遇到问题

Java:手动展开的循环仍然比原始循环快。为什么?

python - 在 Huggingface BERT 模型之上添加密集层

python - 将 PyQt 输出与 python 文件链接

python - 从 Python 中的对象列表中删除对象的最快或最惯用的方法

c# - 对 EF-to-Linq 查询进行排序的最快方法是什么?