有没有更有效的方法来查找元素的索引而不使用列表内置函数?

Is there a more efficient way to find index of an element without using list built-in functions?

我们可以使用 .index() 函数获取列表中元素的索引。 我想知道是否有更有效的方法来查找索引 而无需使用内置函数(列表)。

目前,我使用enumerate编写了以下代码:

x = int(input("Enter a number to get the index:"))
l = [3,11,4,9,1,23,5]
if x in l: # I think this line is unnecessary and is increasing the time. 
    for i, val in enumerate(l):
        #Instead checking for x above can i use
        #if x == val: Don't worry about the indentation I'll fix it.   
        print(f"Index of {x} is {i}.")
else:
    print("Item not found.")

那么,有没有更有效的方法(就花费的时间而言)来完成这个? 我想要一个比我上面写的代码更有效的实现,而不是 .index.

在python

中使用list comprehension
l = [3, 11, 4, 9, 1, 23, 5, 11]
indexes = [index for index in range(len(l)) if l[index] == 11]

输出:

[1, 7]

使用 numpy 查找匹配索引。

import numpy as np

l = [3, 11, 4, 9, 1, 23, 5, 11]
np_array = np.array(l)
item_index = np.where(np_array == 11)
print (item_index)

Numpy效率高:

import random
import time

import numpy as np

limit = 10 ** 7
l = [None] * limit
for i in range(limit):
    l[i] = random.randint(0, 1000000)

start = time.time()
np_array = np.array(l)
item_index = np.where(np_array == 11)
print('time taken by numpy', time.time() - start)

start = time.time()
for index, value in enumerate(l):
    if (value == 11):
        pass
print('time taken by enumerate',time.time() - start)

输出:

time taken by numpy 0.9375550746917725
time taken by enumerate 1.4508612155914307

timeit

import random
import sys
import time
from multiprocessing import Process
from threading import Thread

import numpy as np

start = time.time()
limit = (10 ** 4)
l = [None] * limit
for i in range(limit):
    l[i] = random.randint(0, 1000000)


def testNumpy():
    np_array = np.array(l)
    for i in range(1000):
        value = random.randint(0, 1000000)
        item_index = np.where(np_array == value)


def testEnumerate():
    for i in range(1000):
        randValue = random.randint(0, 1000000)
        for index, value in enumerate(l):
            if (value == randValue):
                pass


def _testNumpy(repeat):
    import timeit
    s = """\
testNumpy()
    """
    print(timeit.timeit(stmt=s, setup="from __main__ import testNumpy", number=repeat, globals=globals()),
          end=":numpy\n")


def _testEnumerate(repeat):
    import timeit
    s = """\
testEnumerate()
        """
    print(timeit.timeit(stmt=s, setup="from __main__ import testEnumerate", number=repeat, globals=globals()),
          end=':enumerate\n')


if __name__ == "__main__":
    repeat = 10
    processes = [Process(target=_testNumpy, args=(repeat,)), Process(target=_testEnumerate, args=(repeat,))]
    for process in processes:
        process.start()

    for process in processes:
        process.join()

输出:

0.2232685430001311:numpy
8.573617108999997:enumerate