【问题标题】:Python linear search with more than one element the same [duplicate]具有多个相同元素的Python线性搜索[重复]
【发布时间】:2021-08-08 11:44:37
【问题描述】:

我刚开始使用python并尝试创建一个简单的线性搜索程序

list1=[4,2,7,5,12,54,21,64,12,32]
x=int(input("Please enter a number to search for :  "))
for i in list1:
    if x==i:
        print("We have found",x,"and it is located at index number",list1.index(i))

我的问题是,如果我将列表更改为 [4,2,7,5,12,54,21,64,12,2,32],它不会输出 2 值的两个位置。

非常感谢任何帮助。

【问题讨论】:

  • 检查here
  • 您是否尝试过调试您的程序?例如检查循环的每个步骤中的 xi 是什么。这将带您进入正确的方向。

标签: python


【解决方案1】:

这是因为您使用的是list1.index(i)

list.index() 仅返回匹配元素的第一次出现。因此,即使您的循环找到任何数字的第二次出现,此函数也只会返回第一次出现的索引。

由于您正在打印搜索元素的索引,因此您可以使用enumerate

>>> list1 = [4,2,7,5,12,54,21,64,12,2,32]
>>> x=int(input("Please enter a number to search for :  "))
Please enter a number to search for :  2
>>> 
>>> for idx, i in enumerate(list1):
...     if x==i:
...         print("We have found",x,"and it is located at index number",idx)
... 
We have found 2 and it is located at index number 1
We have found 2 and it is located at index number 9

enumerate 迭代你的list1,并返回一个tuple 值:在每次迭代中idx, i,其中i 是你的list1 中的数字,idx 是它的索引。

【讨论】:

  • @firestarter 这是否解决了您的问题,还是您需要更多帮助?
猜你喜欢
  • 2020-07-27
  • 1970-01-01
  • 1970-01-01
  • 2014-01-04
  • 2017-06-09
  • 2018-01-17
  • 2021-06-25
  • 1970-01-01
相关资源
最近更新 更多