.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.")
那么,有沒有更好的方法(就所花費的時間而言)來實作這一目標?感謝您的時間和知識。
uj5u.com熱心網友回復:
在 python 中使用串列推導
l = [3, 11, 4, 9, 1, 23, 5, 11]
indexes = [index for index in range(len(l)) if l[index] == 11]
輸出:
[1, 7]
用于numpy查找匹配的索引。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/427799.html
