-1

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

有集合A,集合B和列表C,列表D。集合A和列表C,有像'lion''tiger''cat'这样的元素。集合 B 和列表 D,有 'lion' 'monkey' 'cat' 之类的元素。

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

4

1 回答 1

0

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

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
于 2019-08-30T11:08:47.130 回答