加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:57:05 所属栏目:Python 来源:网络整理
导读:参见英文答案 Which is faster and why? Set or List?????????????????????????????????????3个 哪个更高效,Python中的渐近复杂度(或它们是等价的)是什么? set.add(12)if 12 not in somelist: somelist.append(12) 解决方法 一般来说,这个集合要快得多.对列
参见英文答案 > 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读