You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何通过输入填充列表并查询指定值的索引位置?

实现列表值的索引查询功能

修正后的完整代码

count = 0
myListe = []

# 循环填充5个值到列表
while True:
    value = input("Input 5 values here: ")  
    myListe.append(value)
    count += 1
    if count == 5:
        break  

# 查询目标值的索引
target_value = input("What value do you want to know the position for? ")
try:
    position = myListe.index(target_value)
    print(f"Its position {position}")
except ValueError:
    print("The value is not in the list.")

原代码的问题分析

  1. 变量名拼写错误:查询代码里用了myList,但定义的列表变量是myListe,拼写不一致会导致程序报错。
  2. 逻辑方向错误:你把输入的查询值强制转成整数,然后用这个整数作为索引去取列表元素,这和需求完全相反——我们需要的是根据值找对应的索引,而非用索引找值。
  3. 未处理异常情况:如果用户输入的内容不在列表中,index()方法会抛出ValueError,直接运行会导致程序崩溃,需要用try-except捕获该异常并给出提示。

额外说明

因为input()获取的所有内容都是字符串类型,所以如果列表里的元素是数字(比如你输入的"4"),查询时必须输入完全一致的字符串"4"才能匹配。如果需要支持自动识别数字类型,可以在填充列表时做类型转换,示例如下:

count = 0
myListe = []

while True:
    input_str = input("Input 5 values here: ")
    # 尝试转换为整数,失败则转浮点数,再失败保留字符串
    try:
        value = int(input_str)
    except ValueError:
        try:
            value = float(input_str)
        except ValueError:
            value = input_str
    myListe.append(value)
    count += 1
    if count == 5:
        break  

target_value_input = input("What value do you want to know the position for? ")
# 同样对查询输入做类型转换
try:
    target_value = int(target_value_input)
except ValueError:
    try:
        target_value = float(target_value_input)
    except ValueError:
        target_value = target_value_input

try:
    position = myListe.index(target_value)
    print(f"Its position {position}")
except ValueError:
    print("The value is not in the list.")

内容的提问来源于stack exchange,提问作者oljo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 19:01:24