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) 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
推荐阅读
- google-sheets - Google表格中两个数组之间的联合
- reactjs - 使用 React 路由器从 URL 获取 ID(匹配)
- openssh - 为什么 Google 2FA (libpam) 在 opensuse 中不起作用
- r - 防止 R shiny handsontable 重置为默认值
- c# - 反序列化 JSON 列表
- node.js - 与 Hasura 的 WebSocket 连接不适用于 Node.js 上的 ApolloClient v3
- c - 使用 SSE 向量化在 OpenMP 中将内部循环与残差计算并行化
- linux - 如何在 bash tar 命令中扩展变量
- python - wsgiref simple_服务器无法得到对请求的响应
- java - twitter4j 可以使用新的 Twitter API 吗?