首页 > 解决方案 > 如何在 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.')

标签: python

解决方案


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

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

推荐阅读