Pythons 设置和计算与列表计算
Pythons Set & calculate versus list calculate
在python,我想知道一些事情。(为我的英语道歉)
我想知道 set 和 list
之间的交叉速度
有集合A、集合B和列表C、列表D。
集合A和列表C,有'lion''tiger''cat'这样的元素。
设置B和列表D,有像'lion' 'monkey' 'cat'.
这样的元素
我想知道路口速度(A & B, C & D)(result: lion cat)。
操作 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
在python,我想知道一些事情。(为我的英语道歉) 我想知道 set 和 list
之间的交叉速度有集合A、集合B和列表C、列表D。 集合A和列表C,有'lion''tiger''cat'这样的元素。 设置B和列表D,有像'lion' 'monkey' 'cat'.
这样的元素我想知道路口速度(A & B, C & D)(result: lion cat)。 操作 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