python - intersection() 和 'object for object in set if object in other_set' 之间的速度差异

标签 python performance data-structures set intersection

哪一个更快?一个“更好”吗?基本上我会有两个集合,我想最终从两个列表中得到 一个 匹配项。所以我真的认为 for 循环更像是:

for object in set:
    if object in other_set:
        return object

就像我说的——我只需要一场比赛,但我不确定 intersection() 是如何处理的,所以我不知道它是否更好。此外,如果有帮助,other_set 是一个包含近 100,000 个组件的列表,set 可能有几百个,最多 几千个。

最佳答案

from timeit import timeit

setup = """
from random import sample, shuffle
a = range(100000)
b = sample(a, 1000)
a.reverse()
"""

forin = setup + """
def forin():
    # a = set(a)
    for obj in b:
        if obj in a:
            return obj
"""

setin = setup + """
def setin():
    # original method:
    # return tuple(set(a) & set(b))[0]
    # suggested in comment, doesn't change conclusion:
    return next(iter(set(a) & set(b)))
"""

print timeit("forin()", forin, number = 100)
print timeit("setin()", setin, number = 100)

时间:

>>>
0.0929054012768
0.637904308732
>>>
0.160845057616
1.08630760484
>>>
0.322059185123
1.10931801261
>>>
0.0758695262169
1.08920981403
>>>
0.247866360526
1.07724461708
>>>
0.301856152688
1.07903130641

在设置中将它们放入集合并运行 10000 次而不是 100 次产量

>>>
0.000413064976328
0.152831597075
>>>
0.00402408388788
1.49093627898
>>>
0.00394538156695
1.51841512101
>>>
0.00397715579584
1.52581949403
>>>
0.00421472926155
1.53156769646

因此无论将它们转换为集合是否有意义,您的版本都快得多。

关于python - intersection() 和 'object for object in set if object in other_set' 之间的速度差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6821329/

相关文章:

python - LPTHW : double quotes around CSV. 作家

python - 如何使用文件扩展 sys.path?

python - python 中的列表为空

html - (X)HTML 无效时对浏览器性能有何影响

java - 如何检测树中的循环引用?

data-structures - 一个模块中的 Rc<T>s 和另一个模块中的 Rc<RefCell<T>>s 引用相同的数据

python - 展平 OpenCV/Numpy 数组

C: 将整个文件读入缓冲区并字节交换 buf | ADDECEFA -> 死面

性能测试音频 jmeter

javascript - 嵌套在 Foreach 中的 Map 函数未按预期运行 为什么?