检查列表中是否存在值的最快方法

我与影子孤独终老i 提交于 2020-08-15 23:15:27

问题:

What is the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is? 知道列表中是否存在值(列表中包含数百万个值)及其索引是什么的最快方法是什么?

I know that all values in the list are unique as in this example. 我知道列表中的所有值都是唯一的,如本例所示。

The first method I try is (3.8 sec in my real code): 我尝试的第一种方法是(在我的实际代码中为3.8秒):

a = [4,2,3,1,5,6]

if a.count(7) == 1:
    b=a.index(7)
    "Do something with variable b"

The second method I try is (2x faster: 1.9 sec for my real code): 我尝试的第二种方法是(速度提高了2倍:实际代码为1.9秒):

a = [4,2,3,1,5,6]

try:
    b=a.index(7)
except ValueError:
    "Do nothing"
else:
    "Do something with variable b"

Proposed methods from Stack Overflow user (2.74 sec for my real code): 堆栈溢出用户建议的方法(我的实际代码为2.74秒):

a = [4,2,3,1,5,6]
if 7 in a:
    a.index(7)

In my real code, the first method takes 3.81 sec and the second method takes 1.88 sec. 在我的真实代码中,第一种方法耗时3.81秒,第二种方法耗时1.88秒。 It's a good improvement, but: 这是一个很好的改进,但是:

I'm a beginner with Python/scripting, and is there a faster way to do the same things and save more processing time? 我是使用Python /脚本的初学者,有没有更快的方法来做相同的事情并节省更多的处理时间?

More specific explication for my application: 我的应用程序更具体的说明:

In the Blender API I can access a list of particles: 在Blender API中,我可以访问粒子列表:

particles = [1, 2, 3, 4, etc.]

From there, I can access a particle's location: 从那里,我可以访问粒子的位置:

particles[x].location = [x,y,z]

And for each particle I test if a neighbour exists by searching each particle location like so: 对于每个粒子,我通过搜索每个粒子位置来测试是否存在邻居:

if [x+1,y,z] in particles.location
    "Find the identity of this neighbour particle in x:the particle's index
    in the array"
    particles.index([x+1,y,z])

解决方案:

参考一: https://stackoom.com/question/Vlj9/检查列表中是否存在值的最快方法
参考二: https://oldbug.net/q/Vlj9/Fastest-way-to-check-if-a-value-exists-in-a-list
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!