哪一个更快,一套理解还是一套差异?

2024-05-20 10:45:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两份清单:

from secrets import token_urlsafe

a = [token_urlsafe() for i in range(100)]
b = a[50:]

我需要找出这两个列表之间的区别。我是使用集合理解还是集合差异

Python文档描述了实现这一点的两种方法

设置差异

set(a) - set(b)

Return a new set with elements in the set that are not in the others

ref

集合理解

{i for i in a if i not in b}

Use a set comprehension: {c for c in 'abracadabra' if c not in 'abc'}

ref


Tags: theinfromimporttokenref列表for
1条回答
网友
1楼 · 发布于 2024-05-20 10:45:52

我们可以看到,使用timeit时,集合差分方法的速度更快:

>>> timeit.timeit(lambda: set(a) - set(b), number=100000)
0.37637379999796394

>>> timeit.timeit(lambda: {i for i in a if i not in b}, number=100000)
5.430218600013177

请注意,时间可能因集合a的长度、集合b的长度、公共元素的数量以及它们的公共位置而不同

相关问题 更多 >