检查列表中是否存在值的最快方法 [英] Fastest way to check if a value exists in a list

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

问题描述

知道列表中是否存在值(列表中包含数百万个值)及其索引是什么的最快方法是什么?

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.

我尝试的第一种方法是(在我的实际代码中为3.8秒):

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

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

我尝试的第二种方法是(速度提高了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"

Stack Overflow用户的建议方法(我的实际代码为2.74秒):

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

在我的真实代码中,第一种方法耗时3.81秒,第二种方法耗时1.88秒. 这是一个很好的改进,但是:

In my real code, the first method takes 3.81 sec and the second method takes 1.88 sec. It's a good improvement, but:

我是使用Python/脚本的初学者,有没有更快的方法来完成相同的事情并节省更多的处理时间?

I'm a beginner with Python/scripting, and is there a faster way to do the same things and save more processing time?

我的应用程序的更具体说明:

在Blender API中,我可以访问粒子列表:

In the Blender API I can access a list of particles:

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])

推荐答案

7 in a

最快捷的方法.

您也可以考虑使用set,但是从列表中构造该集合所花费的时间可能比进行更快的成员资格测试所节省的时间更多.唯一可以确定的基准就是基准测试. (这还取决于您需要执行哪些操作)

You can also consider using a set, but constructing that set from your list may take more time than faster membership testing will save. The only way to be certain is to benchmark well. (this also depends on what operations you require)

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

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