知道列表中是否存在值(列表中包含数百万个值)及其索引是什么的最快方法是什么?
我知道列表中的所有值都是唯一的,如本例所示。
我尝试的第一种方法是(在我的实际代码中为 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])7 in a最清晰,最快的方法。
您也可以考虑使用set ,但是从列表中构造该 set 所花费的时间可能比更快的成员资格测试所节省的时间更多。唯一可以确定的基准就是基准测试。 (这还取决于您需要执行哪些操作) 
正如其他人所述,对于大型列表, in可能会非常慢。这是in , set和bisect的性能比较。请注意,时间(以秒为单位)是对数刻度。 
测试代码:
import random
import bisect
import matplotlib.pyplot as plt
import math
import time
def method_in(a,b,c):
    start_time = time.time()
    for i,x in enumerate(a):
        if x in b:
            c[i] = 1
    return(time.time()-start_time)   
def method_set_in(a,b,c):
    start_time = time.time()
    s = set(b)
    for i,x in enumerate(a):
        if x in s:
            c[i] = 1
    return(time.time()-start_time)
def method_bisect(a,b,c):
    start_time = time.time()
    b.sort()
    for i,x in enumerate(a):
        index = bisect.bisect_left(b,x)
        if index < len(a):
            if x == b[index]:
                c[i] = 1
    return(time.time()-start_time)
def profile():
    time_method_in = []
    time_method_set_in = []
    time_method_bisect = []
    Nls = [x for x in range(1000,20000,1000)]
    for N in Nls:
        a = [x for x in range(0,N)]
        random.shuffle(a)
        b = [x for x in range(0,N)]
        random.shuffle(b)
        c = [0 for x in range(0,N)]
        time_method_in.append(math.log(method_in(a,b,c)))
        time_method_set_in.append(math.log(method_set_in(a,b,c)))
        time_method_bisect.append(math.log(method_bisect(a,b,c)))
    plt.plot(Nls,time_method_in,marker='o',color='r',linestyle='-',label='in')
    plt.plot(Nls,time_method_set_in,marker='o',color='b',linestyle='-',label='set')
    plt.plot(Nls,time_method_bisect,marker='o',color='g',linestyle='-',label='bisect')
    plt.xlabel('list size', fontsize=18)
    plt.ylabel('log(time)', fontsize=18)
    plt.legend(loc = 'upper left')
    plt.show()