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

参见英文答案 > Which is faster and why? Set or List?                                    3个
哪个更高效,Python中的渐近复杂度(或它们是等价的)是什么?

set.add(12)

if 12 not in somelist:
    somelist.append(12)

解决方法

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

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...