Python 这是一个线性搜索代码。如何返回该值的位置而不是返回true?
如果值在列表中,如何返回该值的位置,而不是返回true?使用Python 这是一个线性搜索代码。如何返回该值的位置而不是返回true?,python,python-3.x,linear-search,Python,Python 3.x,Linear Search,如果值在列表中,如何返回该值的位置,而不是返回true?使用list.index(): 文档:如果您想完全保留代码,可以使用enumerate获取索引位置 def linearSearch(列表,目标): 对于ix,枚举(列表)中的项目: 如果项目==目标: 返回ix 返回错误 当您遇到重复的目标值时会发生什么情况,您想要什么aList.index(target)如果您希望第一次出现索引,则可以使用此选项回答您的问题吗?等等,你为什么要编辑代码?这个问题已经没有任何意义了。它应该适用于任何人nu
list.index()
:
文档:如果您想完全保留代码,可以使用enumerate获取索引位置
def linearSearch(列表,目标):
对于ix,枚举(列表)中的项目:
如果项目==目标:
返回ix
返回错误
当您遇到重复的目标值时会发生什么情况,您想要什么aList.index(target)
如果您希望第一次出现索引,则可以使用此选项回答您的问题吗?等等,你为什么要编辑代码?这个问题已经没有任何意义了。它应该适用于任何人number@ivanlin2020你是什么意思?它应该返回数字的位置,数字可以change@ivanlin2020我还是不明白你的意思。你能举个例子吗?对于我的代码,我希望它返回位置,你可以看到它是如何返回true和false的,是的,我希望返回位置而不是返回false
是有问题的,因为false==0
@ivanlin2020想要摆脱“true”响应。没有关于“False”响应的评论。我知道,我是说如果找不到值,您应该返回除False
以外的内容,因为0
是一个可能的索引,False==0
。例如,linearSearch(testList,3)
->0
<代码>线性搜索(testList,16)->False
。作为修复,您可以使用-1
,如str.find()
。
def main():
testList = [3, 1, 8, 1, 5, 2, 21, 13]
print("searching for 5 in", testList,"...")
searchResult1 = linearSearch(testList, 5)
print(searchResult1)
def linearSearch(aList, target):
for item in aList:
if item == target:
return True
return False
main()
>>> testList = [3, 1, 8, 1, 5, 2, 21, 13]
>>> testList.index(5)
4
>>> testList.index(16)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 16 is not in list
>>> 5 in testList
True
>>> 16 in testList
False