Python化学式量计算项目遇IndexError: list index out of range错误求助
解决化学式式量计算中的IndexError问题
问题描述
本人首次进行项目开发,编写的Python代码用于计算含单字母元素、一位数系数的化学式的式量(示例:输入H2O1时输出18)。尝试调整intlength及myatom、myatomnum的索引后,仍反复出现IndexError: list index out of range错误,且无法使用代码外的其他函数。
代码如下:
atom = ['H', 'B', 'C', 'N', 'O', 'F', 'P', 'S', 'K'] atommass = [1, 10.8, 12, 14, 16, 19, 31, 32, 39.1] myatom = [] myatomnum = [] answer = input() length = len(answer) intlength = int(length) mm = [] for x in range(length): if (answer[x] > 'A' and answer[x] < 'Z') : for i in range (9): if (answer[x] == atom[i]): myatom.append(atommass[i]) else : for ii in range (10): if (answer[x] == ii): myatomnum.append(ii) for plus in range(int(intlength/2)): mm.append(int(myatom[plus])*int(myatomnum[plus])) result = 0 for x in mm: result += x print(result)
报错信息(翻译后):
Makefile:6: 目标 'py3_run' 的生成规则失败 make: *** [py3_run] 错误 1 回溯(最近的调用最后): 文件 "/goorm/Main.out", 第24行, 于 <module> mm.append(int(myatom[plus])*int(myatomnum[plus])) 索引错误:列表索引超出范围
错误原因分析
- 字符与数字类型不匹配:判断数字时,
answer[x]是字符串类型,ii是整数类型,answer[x] == ii永远不成立,导致myatomnum列表始终为空,后续访问索引必然报错。 - 字母判断逻辑漏洞:用
answer[x] > 'A' and answer[x] < 'Z'判断大写字母,漏掉了等于'A'或'Z'的情况,逻辑不严谨。 - 循环次数假设错误:
range(int(intlength/2))默认输入长度为偶数,但如果输入省略系数1的化学式(如H2O),长度为奇数,会导致循环次数与实际元素数量不匹配;同时即使长度为偶数,myatomnum为空的情况下依然会触发索引越界。
修正后的代码
atom = ['H', 'B', 'C', 'N', 'O', 'F', 'P', 'S', 'K'] atommass = [1, 10.8, 12, 14, 16, 19, 31, 32, 39.1] myatom = [] myatomnum = [] answer = input().strip() length = len(answer) x = 0 while x < length: # 处理大写字母元素 if answer[x].isupper(): # 匹配对应原子量 for i in range(len(atom)): if answer[x] == atom[i]: myatom.append(atommass[i]) break x += 1 # 处理后续数字系数,无数字则默认系数为1 if x < length and answer[x].isdigit(): myatomnum.append(int(answer[x])) x += 1 else: myatomnum.append(1) else: print("输入格式错误,请输入元素+一位数系数的组合") exit() # 计算总式量 result = 0 for mass, num in zip(myatom, myatomnum): result += mass * num print(result)
修正说明
- 修复数字判断逻辑:用
isdigit()判断字符是否为数字,并将字符串转为整数存入myatomnum。 - 处理省略系数的场景:元素后无数字时自动添加系数1,兼容
H2O这类常见输入格式。 - 优化遍历方式:用while循环按「元素+系数」的成对逻辑遍历,确保每个元素都对应一个系数,避免索引混乱。
- 严谨的元素判断:用
isupper()判断大写字母,覆盖所有合法元素标识。 - 避免索引不匹配:用
zip()同时遍历原子量和系数列表,确保两个列表长度一致,彻底解决索引越界问题。
测试示例:
- 输入
H2O1,输出18.0 - 输入
H2O,输出18.0 - 输入
C6,输出72.0
内容的提问来源于stack exchange,提问作者Clare Hwang
相关产品推荐
相关产品推荐

