如何在Python中从左到右进行线性搜索



有没有一种方法可以进行线性搜索,从列表的左到右进行搜索,直到它们收敛并找到要搜索的关键字?

def linear_search(alist,key):
for i in range(len(alist)):
if alist[i] == key:
return i
return -1

alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
while True:
key = int(input("The number to search for: "))
index = linear_search(alist, key)
if index >= 0:
print(f"{key} was found at index {index}.")
else:
print(f'{key} was not found.')

您可以更改范围函数,使用以下命令从右到左返回索引:

for i in range(len(alist)-1,-1,-1):
# your logic

您还可以使用内置模块来跟踪列表中项目的索引。它来了:

for index, value in enumerate(mylist):
# <logic>

最新更新