相关疑难解决方法(0)

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

我正在寻找最快的方法来了解列表中是否存在值(列表中包含数百万个值)以及它的索引是什么?我知道列表中的所有值都是唯一的,就像我的例子一样.

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

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

if a.count(7) == 1:
    b=a.index(7)
    "Do something with variable b"
Run Code Online (Sandbox Code Playgroud)

我尝试的第二种方法是(快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"
Run Code Online (Sandbox Code Playgroud)

Stackoverflow用户提出的方法(我的实际代码为2.74秒):

a = [4,2,3,1,5,6]
if 7 in a:
    a.index(7)
Run Code Online (Sandbox Code Playgroud)

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

我是Python /脚本的初学者,我想知道是否有最快的方法可以做同样的事情并节省更多的处理时间?

我的应用程序更具体的解释:

在blender的API中,a可以访问粒子列表:

particles = [1, 2, 3, 4, etc.]
Run Code Online (Sandbox Code Playgroud)

从那里,我可以访问它的位置:

particles[x].location = [x,y,z]
Run Code Online (Sandbox Code Playgroud)

我通过搜索每个粒子的位置测试每个粒子是否存在邻居,如:

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])
Run Code Online (Sandbox Code Playgroud)

python performance list

734
推荐指数
10
解决办法
170万
查看次数

标签 统计

list ×1

performance ×1

python ×1