哪一个更有表现力,在Python中渐近复杂性(或者它们是等价的)是什么?
set.add(12)
if 12 not in somelist:
somelist.append(12)
发布于 2017-01-04 06:30:07
一般来说,这套节目要快得多。列表中成员资格的测试是O(n),与列表的大小成线性关系。添加到集合中的是O(1),与列表中的项目数无关。除此之外,列表代码执行两个函数调用:一个用于检查列表中是否有12个函数,另一个用于添加它,而set操作只执行一个调用。
注意,列表解决方案可以是快速的,但是,当项目不需要添加到列表中,因为它是在列表的早期找到的。
# Add item to set
$ python -m timeit -s 's = set(range(100))' 's.add(101)'
10000000 loops, best of 3: 0.0619 usec per loop
# Add item not found in list
$ python -m timeit -s 'l = list(range(100))' 'if 101 not in l: l.append(101)'
1000000 loops, best of 3: 1.23 usec per loop
# "Add" item found early in list
$ python -m timeit -s 'l = list(range(100))' 'if 0 not in l: l.append(0)'
10000000 loops, best of 3: 0.0214 usec per loop
# "Add" item found at the end of the list
$ python -m timeit -s 'l = list(range(102))' 'if 101 not in l: l.append(101)'
1000000 loops, best of 3: 1.24 usec per loop
https://stackoverflow.com/questions/41466070
复制相似问题