当您在 "test"in a
中执行类似操作时,其中 a
是一个列表,python 是在列表上进行顺序搜索还是创建一个哈希表表示优化查找?在应用程序中,我需要这个,因为我将在列表中进行大量查找,所以最好先执行 b = set(a)
之类的操作,然后执行 "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.
不要使用列表,使用 set()
反而。它具有您想要的特性,包括超快的 in
测试。
我已经看到在将一个列表更改为一组的地方(主要是繁重的数字运算)加速了 20 倍甚至更高。
关于python - 在python中搜索列表的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5993621/