检查列表中是否存在值的最快方法
我尝试的第一个方法是(实际代码中的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)
更具体地解释我的应用程序:
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])
慕尼黑5688855
DIEA
相关分类