faster membership testing in python than set()(python 中的成员资格测试比 set() 更快)
问题描述
我必须检查包含 10-100k 这些元素的列表中是否存在数百万个元素(20-30 个字母 str).在 python 中有没有比 set()
更快的方法?
I have to check presence of millions of elements (20-30 letters str) in the list containing 10-100k of those elements. Is there faster way of doing that in python than set()
?
import sys
#load ids
ids = set( x.strip() for x in open(idfile) )
for line in sys.stdin:
id=line.strip()
if id in ids:
#print fastq
print id
#update ids
ids.remove( id )
推荐答案
set
尽可能快.
但是,如果您重写代码以创建 set
一次,而不更改它,则可以使用 frozenset
内置类型.除了不可变之外,它完全一样.
However, if you rewrite your code to create the set
once, and not change it, you can use the frozenset
built-in type. It's exactly the same except immutable.
如果您仍然遇到速度问题,您需要通过其他方式加速您的程序,例如使用 PyPy 而不是 cPython.
If you're still having speed problems, you need to speed your program up in other ways, such as by using PyPy instead of cPython.
这篇关于python 中的成员资格测试比 set() 更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python 中的成员资格测试比 set() 更快


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01