简体   繁体   English

Python 设置和计算与列表计算

[英]Pythons Set & calculate versus list calculate

In python, I wonder something.(Apologize my english) I wonder intersection speed between set and list在python中,我想知道一些事情。(道歉我的英语)我想知道集合和列表之间的交叉速度

There is set A, set B and list C, list D. set A and list C, there is elements like 'lion' 'tiger' 'cat'.有集合 A、集合 B 和列表 C、列表 D。集合 A 和列表 C,有像“狮子”“老虎”“猫”这样的元素。 set B and list D, there is elements like 'lion' 'monkey' 'cat'.设置 B 和列表 D,有像 'lion' 'monkey' 'cat' 这样的元素。

I want to know intersection speed(A & B, C & D)(result: lion cat).我想知道路口速度(A & B, C & D)(结果:狮子猫)。 operation A & B is faster than double for loop C and D???操作 A 和 B 比循环 C 和 D 的两倍要快???

Here is a way to compare several code snippets on time performance.这是一种比较几个关于时间性能的代码片段的方法。 Note that the actual execution times are system dependent, but the ratio of the performances should be approximately equal on different machines.请注意,实际执行时间取决于系统,但不同机器上的性能比率应该大致相等。

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