在Python中搜索列表的最快方法 [英] Fastest way to search a list in python

查看:518
本文介绍了在Python中搜索列表的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你在中做一些像test这样的事情,其中​​ a 是一个列表,python会执行顺序搜索在列表上还是创建一个哈希表表示来优化查找?在应用程序中,我需要这样做,因为我将在列表上做很多查找,所以最好做一些类似于 b = set(a)然后testin b ?另外请注意,我将拥有的值列表将不会有重复的数据,我实际上并不关心它所处的顺序;我只需要能够检查一个值的存在。

解决方案


还要注意我将拥有的价值清单将不会有重复的数据,我实际上并不关心它的订单;我只需要能够检查一个值的存在。

不要使用列表,使用 set() 测试中快速的



我已经看到了20倍的加速和更高的地方(主要是大数字嘎吱嘎吱),其中一个列表更改为一套。

When you do something like "test" in a where a is a list does python do a sequential search on the list or does it create a hash table representation to optimize the lookup? In the application I need this for I'll be doing a lot of lookups on the list so would it be best to do something like b = set(a) and then "test" in b? Also note that the list of values I'll have won't have duplicate data and I don't actually care about the order it's in; I just need to be able to check for the existence of a value.

解决方案

Also note that the list of values I'll have won't have duplicate data and I don't actually care about the order it's in; I just need to be able to check for the existence of a value.

Don't use a list, use a set() instead. It has exactly the properties you want, including a blazing fast in test.

I've seen speedups of 20x and higher in places (mostly heavy number crunching) where one list was changed for a set.

这篇关于在Python中搜索列表的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆