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

将全名字符串存入二维列表时触发索引越界错误,如何修复?

修复索引越界错误的方案

你的代码里有几个关键问题导致了"list out of range"错误,逐个修正即可:

  • 错误的列表初始化:y = [][1] 是完全无效的写法,空列表无法直接通过索引[1]访问,应该把y初始化为空列表:y = []
  • 直接索引未创建的元素:循环里直接给y[i][0]赋值,但y一开始是空的,根本不存在第i个元素,应该先创建包含姓名的子列表,再添加到y中
  • 空格处理不当:原字符串按逗号分割后,每个姓名前有空格,直接用split(" ")会得到包含空字符串的列表,比如['', 'Manuella', 'Germanos'],需要先去掉前后空格再分割

修复后的完整代码:

string1 = "Charbel Daoud, Manuella Germanos, Anis Ismael"

x = string1.split(",")
print(x)

y = []
for j in x:
    # 先去掉前后空格,再分割姓名(split无参数自动处理任意空白)
    div = j.strip().split()
    # 将分割后的姓和名作为子列表添加到y中
    y.append([div[0], div[1]])

print(y)
# 输出:[['Charbel', 'Daoud'], ['Manuella', 'Germanos'], ['Anis', 'Ismael']]

如果你想更简洁,还可以用列表推导式一行完成:

string1 = "Charbel Daoud, Manuella Germanos, Anis Ismael"
y = [name.strip().split() for name in string1.split(",")]
print(y)

这样就能实现你要的效果:y[0][0]是"Charbel",y[0][1]是"Daoud",以此类推。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:24:31