Python中的线性搜索,有多个相同元素

10 浏览
0 Comments

Python中的线性搜索,有多个相同元素

这个问题已经有了答案

在列表中查找项目的索引

我刚开始学习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值的两个位置。

非常感谢任何帮助。

admin 更改状态以发布 2023年5月20日
0
0 Comments

这是因为您正在使用list1.index(i)。\nlist.index()仅返回匹配元素的第一个出现。因此,即使您的循环正在查找任何数字的第二次出现,此函数也仅返回第一次出现的索引。\n由于您正在打印所搜索元素的索引,因此可以使用enumerate来实现:\n

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

\nenumerate迭代您的list1,并在每个迭代中返回一个tuple值:idx,i,其中i是您的list1中的数字,而idx是它的索引。

0