首页 > 解决方案 > 具有多个相同元素的 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值的两个位置。

任何帮助深表感谢。

标签: python

解决方案


这是因为您正在使用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是它的索引。


推荐阅读