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

Python新手遇IndexError: list index out of range问题求助

问题原因与解决方法

错误根源

你定义boy_names和girl_names时,列表内的字符串之间未用逗号分隔。Python会自动将相邻的字符串字面量拼接成单个完整字符串,导致这两个列表实际都只有1个元素,而非你预期的6个元素。

比如['brendan ' 'john ' ...]会被解析为['brendan john ben zach pete ralph'],是一个长度为1的列表。当你尝试访问names[1][1]时,names[1]对应girl_names,它仅存在索引0的元素,索引1不存在,因此抛出IndexError: list index out of range。

修复代码

给每个字符串之间添加逗号即可:

boy_names = ['brendan', 'john', 'ben', 'zach', 'pete', 'ralph']

girl_names = ['lauren', 'makenna', 'kayley', 'mom', 'olivia', 'dingus']

names = [boy_names, girl_names]

print(names[1][1])  # 输出: makenna

注:你原字符串末尾的空格可根据需求保留或移除,不影响列表结构,仅会改变字符串本身的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:51:19