检查列表中是否存在值的最快方法知道一个值是否存在于一个列表中(一个包含数百万个值的列表)以及它的索引是什么的最快方法是什么?我知道列表中的所有值都是唯一的,如本例所示。我尝试的第一个方法是(实际代码中的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"来自堆栈溢出用户的建议方法(实际代码为2.74秒):a = [4,2,3,1,5,6]if 7 in a:
a.index(7)在我的实际代码中,第一个方法需要3.81秒,第二个方法需要1.88秒。这是一个很好的改进,但是:我是Python/脚本的初学者,有更快的方法来做同样的事情并节省更多的处理时间吗?更具体地解释我的应用程序:在Blender API中,我可以访问一个粒子列表:particles = [1, 2, 3, 4, etc.]从那里,我可以进入粒子的位置:particles[x].location = [x,y,z]对于每个粒子,我通过搜索每个粒子的位置来检验是否存在邻居,如下所示: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])
3 回答

慕尼黑5688855
TA贡献1848条经验 获得超2个赞
7 in a
set

DIEA
TA贡献1820条经验 获得超2个赞
def check_availability(element, collection: iter): return element in collection
使用
check_availability('a', [1,2,3,4,'a','b','c'])
添加回答
举报
0/150
提交
取消