【问题标题】:This is a linearSearch code. Instead of returning true how can I return the position of that value?这是一个线性搜索代码。我如何返回该值的位置,而不是返回 true?
【发布时间】:2020-12-13 21:27:16
【问题描述】:
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?

【问题讨论】:

  • 当你遇到重复的目标值时会发生什么,你想要什么? aList.index(target) 如果您想要首次出现索引,则可以使用
  • 这能回答你的问题吗? Finding the index of an item in a list
  • 等等,你为什么要编辑代码?这个问题已经没有任何意义了。

标签: python python-3.x linear-search


【解决方案1】:

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

文档:Common Sequence Operations

【讨论】:

  • @ivanlin2020 什么意思?
  • 所以它应该返回数字的位置并且数字可能会改变
  • @ivanlin2020 我仍然不确定你的意思。你能举个例子吗?
  • 对于我的代码,我希望它返回位置,你看它是如何返回真假的,是的,我想返回位置
  • 是的,这就是我的回答解释了如何做...?
【解决方案2】:

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

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

【讨论】:

  • 返回False 是有问题的,因为False == 0
  • @ivanlin2020 想要摆脱“True”响应。没有关于“虚假”回复的评论。
  • 我知道,我的意思是如果找不到该值,您应该返回除False 以外的其他值,因为0 是一个可能的索引,而False == 0。例如linearSearch(testList, 3) -> 0linearSearch(testList, 16) -> False。作为修复,您可以使用-1,例如str.find()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多