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

新手上路,请多包涵

检查一个值是否存在于一个非常大的列表中的最快方法是什么?

原文由 Jean-Francois Gallant 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 218
2 个回答
7 in a

最清晰,最快的方法。

您也可以考虑使用 set ,但是从您的列表构建该集合可能需要比更快的成员测试节省的时间更多的时间。唯一可以确定的方法是做好基准测试。 (这也取决于你需要什么操作)

原文由 Rafe Kettler 发布,翻译遵循 CC BY-SA 3.0 许可协议

正如其他人所说, in 对于大型列表来说可能非常慢。以下是 insetbisect 的一些性能比较。请注意时间(以秒为单位)是对数刻度。

在此处输入图像描述

测试代码:

 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 = []

    # adjust range down if runtime is too long or up if there are too many zero entries in any of the time_method lists
    Nls = [x for x in range(10000, 30000, 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(method_in(a, b, c))
        time_method_set_in.append(method_set_in(a, b, c))
        time_method_bisect.append(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.yscale('log')
    plt.show()

profile()

原文由 xslittlegrass 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题