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

Python列表index方法异常:重复值时始终返回索引0问题排查

问题排查与修复方案

问题现象

以下Python代码用于根据输入的六组三位数输出对应单位前缀组合:

pfz0 = ["","centi","milli","micri","nani","pici","femti"] # z for zeta
illion = ["llion","illion"]

a0_ni = input("first 3 digits:")
a0 = int(a0_ni) # femti

b0_ni = input("next 3       digits:")
b0 = int(b0_ni) # pici

c0_ni = input("next 3 digits :")
c0 = int(c0_ni) # nani

d0_ni = input("next 3 digits :")
d0 = int(d0_ni) # micri

e0_ni = input("next 3 digits:")
e0 = int(e0_ni) # milli

f0_ni = input("next 3 digits :")
f0 = int(f0_ni) # centi

zl = [f0,e0,d0,c0,b0,a0]

if isinstance(a0,int) and isinstance(b0,int) and isinstance(c0,int) and isinstance(d0,int)  and isinstance(e0,int) and isinstance(f0,int) and a0 < 1000 and b0 < 1000 and c0 < 1000 and d0 < 1000 and e0 < 1000 and 10 < f0 < 1000:

    print(pfz0[int(zl.index(a0)) + 1] + pfz0[int(zl.index(b0)) + 1] + pfz0[int(zl.index(c0)) + 1] + pfz0[int(zl.index(d0)) + 1] + pfz0[int(zl.index(e0)) + 1] + illion[0])

elif zl == [0,0,0,0,0,0]:
    print("zero")
    print("10^-inf")

else:
    print("error")

当输入重复的三位数(如六组555)时,代码输出centicenticenticenticenticenti,但预期输出应为femtipicinanimicrimillicenti;非重复输入时运行正常。

问题原因

问题出在zl.index(x)方法的特性:该方法只会返回列表中第一个匹配元素的索引。当所有输入值重复时,不管是a0、b0还是其他变量,zl.index()都会返回0,导致每次取到的pfz0元素都是pfz0[0+1]即centi,最终输出重复的前缀。

此外,代码中zl的顺序是[f0,e0,d0,c0,b0,a0],对应centi到femti的固定映射关系,但index()方法无法区分相同值在列表中的不同位置,完全违背了原本的对应逻辑。

修复方案

直接利用代码注释中已经明确的变量与前缀的固定对应关系,不需要通过zl列表和index()方法取值:

  • a0对应femti → pfz0[6]
  • b0对应pici → pfz0[5]
  • c0对应nani → pfz0[4]
  • d0对应micri → pfz0[3]
  • e0对应milli → pfz0[2]
  • f0对应centi → pfz0[1]

修改后的核心逻辑:移除冗余的zl列表和isinstance判断(input转int后必然是整数类型),直接按固定索引拼接结果。

完整修复后代码

pfz0 = ["","centi","milli","micri","nani","pici","femti"] # z for zeta
illion = ["llion","illion"]

a0_ni = input("first 3 digits:")
a0 = int(a0_ni) # femti

b0_ni = input("next 3       digits:")
b0 = int(b0_ni) # pici

c0_ni = input("next 3 digits :")
c0 = int(c0_ni) # nani

d0_ni = input("next 3 digits :")
d0 = int(d0_ni) # micri

e0_ni = input("next 3 digits:")
e0 = int(e0_ni) # milli

f0_ni = input("next 3 digits :")
f0 = int(f0_ni) # centi

if a0 < 1000 and b0 < 1000 and c0 < 1000 and d0 < 1000 and e0 < 1000 and 10 < f0 < 1000:
    print(pfz0[6] + pfz0[5] + pfz0[4] + pfz0[3] + pfz0[2] + illion[0])
elif [f0,e0,d0,c0,b0,a0] == [0,0,0,0,0,0]:
    print("zero")
    print("10^-inf")
else:
    print("error")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 15:05:11