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

具有多个相同元素的Python线性搜索,python,Python,我刚开始使用python,并尝试创建一个简单的线性搜索程序 list1=[4,2,7,5,12,54,21,64,12,32] x=int(输入(“请输入要搜索的数字:”) 对于清单1中的i: 如果x==i: 打印(“我们找到了”,x,“它位于索引编号”,列表1。索引(i)) 我的问题是,如果我将列表更改为[4,2,7,5,12,54,21,64,12,2,32]它不会同时输出2值的两个位置 非常感谢您的帮助。这是因为您正在使用list1.index(i) list.index()仅返回匹配元

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

list1=[4,2,7,5,12,54,21,64,12,32]
x=int(输入(“请输入要搜索的数字:”)
对于清单1中的i:
如果x==i:
打印(“我们找到了”,x,“它位于索引编号”,列表1。索引(i))
我的问题是,如果我将列表更改为
[4,2,7,5,12,54,21,64,12,2,32]
它不会同时输出
2
值的两个位置


非常感谢您的帮助。

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

检查您是否尝试调试程序?e、 g.检查循环每个步骤中的
x
i
。这会把你带到正确的方向。@firestarter这解决了你的问题,还是你需要更多的帮助?