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

如何在Python中从左到右进行线性搜索?,python,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

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

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>
    
对于索引,枚举中的值(mylist):
# 

那么您发布的代码有什么问题?在我看来,它应该工作得很好,并且完全符合你在问题中提出的要求。你是在问,它们是线性搜索的内置函数吗?它显示了列表索引range@Studyante请从名单的第二栏中减去一个。检查更新的答案