Python list.append如果不在列表中而不是set.add性能

GL2*_*014 3 python

哪个更高效,Python中的渐近复杂度(或它们是等价的)是什么?

set.add(12)

if 12 not in somelist:
    somelist.append(12)
Run Code Online (Sandbox Code Playgroud)

che*_*ner 7

一般来说,这个集合要快得多.对列表中的成员资格的测试是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
Run Code Online (Sandbox Code Playgroud)