python 代码常用in来判断一个元素是否在list中,这个判断的时间复杂度是多少呢?
in list : o(n)
in set : o(1)
in dict : o(1)
具体的时间差多少呢,跑了下数据,具体如下
list1 = list(range(100000))
%timeit 1 in list1
51.3 ns ± 4.23 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit 100 in list1
1.33 µs ± 106 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit 10000 in list1
130 µs ± 10.9 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit 100000 in list1
1.48 ms ± 117 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit 10000000 in list1
1.44 ms ± 175 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# 寻找的元素在list中位置前后会影响取出数据的时间,最后两次都是1.48ms了,
# 并且位置对查找时间的影响基本是线性的
set1 = set(range(100000))
%timeit 1 in set1
47.7 ns ± 5.93 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit 100 in set1
43.3 ns ± 1.35 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit 10000 in set1
59.6 ns ± 1.38 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit 100000 in set1
44.4 ns ± 1.38 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit 10000000 in set1
60.4 ns ± 2.82 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
# set 就很平均,dict跟set是一样的就不多赘述。