python - 具有多个相同元素的 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
值的两个位置。
任何帮助深表感谢。
解决方案
这是因为您正在使用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
是它的索引。
推荐阅读
- javascript - 从数据库中删除记录后重新加载页面(表)的问题
- tcl - 在 Tcl 脚本中转换列表中的列
- mbtiles - 为什么 Tippecanoe 将 geojson 文件转换为 pbf 矢量切片会导致纬度/经度放置不正确?
- bash - Centos 7 - 脚本未从 init d 运行 - 手动使用&它在后台启动
- python - 使用次轴线图制作分类或分组条形图
- r - R ggplot2:如何跨子组箱线图绘制 2 组的平均线?
- r - 如何修改函数以提取 R 中的某些回归系数
- azure-devops - Azure DevOps 扩展的条件上下文菜单?
- php - 来自 github 的 PHPmailer 是否仅用于您的本地主机?
- ios - 从 Objective-C 调用 Swift 扩展函数的语法