这是一个linearSearch代码.与其返回true,我如何返回该值的位置


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()

如果值在列表中,我如何返回该值的位置,而不是返回true?

使用list.index():

>>> 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

顺便说一下,要检查会员资格,请使用in:

>>> 5 in testList
True
>>> 16 in testList
False

文档:通用序列操作

如果您想完全保留代码,可以使用enumerate来获取索引位置。

def linearSearch(aList, target):
for ix, item in enumerate(aList):
if item == target:
return ix
return False 

最新更新