成员运算符的目的:用于判断一个元素是否在容器中
成员运算符:返回的是bool
In [68]: 3 in [1, 2 ,3 ,4 ]
Out[68]: True
In [69]: 10 in [1, 2, 3, 4]
Out[69]: False
In [71]: 10 not in [1, 2, 3, 4]
Out[71]: True
In [72]: ‘love‘ in ‘i love python‘
Out[72]: True
集合的成员运算符和其他的线性结构的时间复杂度不同
成员运算:
总结:
In [74]: lst = list(range(10000))
In [75]: s = set(range(10000))
In [76]: %%timeit
...: -1 in lst
...:
10000 loops, best of 3: 125 μs per loop
In [77]: %%timeit # 更快
...: -1 in s
...:
The slowest run took 39.70 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 45 ns per loop
做成员运算的时候, 集合的效率远高于列表
In [78]: lst2 = list(range(100))
In [79]: %%timeit
...: -1 in lst2
...:
1000000 loops, best of 3: 1.29 μs per loop
做成员运算时, 运算的效率和列表的规模有关
In [80]: s2 = set(range(100))
In [81]: %%timeit
...: -1 in s2
...:
10000000 loops, best of 3: 39.1 ns per loop
做成员运算时, 集合的效率和集合的规模无关。
原文:https://www.cnblogs.com/cishi/p/13023174.html