繁体   English   中英

Python 设置和计算与列表计算

[英]Pythons Set & calculate versus list calculate

在python中,我想知道一些事情。(道歉我的英语)我想知道集合和列表之间的交叉速度

有集合 A、集合 B 和列表 C、列表 D。集合 A 和列表 C,有像“狮子”“老虎”“猫”这样的元素。 设置 B 和列表 D,有像 'lion' 'monkey' 'cat' 这样的元素。

我想知道路口速度(A & B, C & D)(结果:狮子猫)。 操作 A 和 B 比循环 C 和 D 的两倍要快???

这是一种比较几个关于时间性能的代码片段的方法。 请注意,实际执行时间取决于系统,但不同机器上的性能比率应该大致相等。

import timeit

setup = '''\
A = {'dog', 'cat', 'horse'}
B = {'monkey', 'horse', 'dog'}
'''

statement = '''\
intersection = A & B
'''

timeit.timeit(stmt=statement, setup=setup, number=100000)
# 0.0126 sec

setup2 = '''\
C = ['dog', 'cat', 'horse']
D = ['monkey', 'horse', 'dog']
'''

statement2 = '''\
intersection = C[:]
for i in D:
    if i not in intersection:
        intersection.append(i)
'''

timeit.timeit(stmt=statement2, setup=setup2, number=100000)
# 0.0312 sec

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM