You need to enable JavaScript to run this app. Python向空列表按索引赋值用户输入值时报list assignment index out of range错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python向空列表按索引赋值用户输入值时报list assignment index out of range错误如何解决

错误产生原因
  • 你初始化的mu1、sigma都是空列表,Python空列表不存在任何有效索引,直接通过mu1[i] = xxx的方式赋值,是试图修改列表已存在的索引位置的元素,空列表没有对应位置的索引,因此触发list assignment index out of range错误。
  • 除此之外你的代码还有两处隐含错误:
    1. 循环范围使用range(1, plots),range的结束值为开区间,会少执行一次循环,无法收集到用户输入的plots数量的对应数据
    2. 你初始化的标准差列表变量名为sigma,但循环赋值时用的是sigma1,变量名不匹配会额外触发NameError。
修复方案

这里提供两种常用的实现方式,任选其一即可:

方案1:使用append()方法追加元素(更符合Python使用习惯)

不需要预先指定列表长度,每次收集到用户输入后直接追加到列表末尾即可:

mu1 = []
sigma = []
plots = int(input("please enter number of plots : "))

# 循环次数匹配输入的plots数量,序号从1开始符合用户输入提示的语义
for i in range(1, plots + 1) :
    mu1.append(float(input("Enter the mean for the " + str(i) + " plot :")))
    sigma.append(float(input("Enter the STD for the " + str(i) + " plot :")))

方案2:预先初始化指定长度的列表,按索引赋值

如果你确实需要通过索引赋值的方式操作,可以先初始化对应长度的列表占位:

plots = int(input("please enter number of plots : "))
# 先初始化长度为plots的列表,用None占位
mu1 = [None] * plots
sigma = [None] * plots

# 这里如果要对应用户提示的序号从1开始,索引要减1匹配列表从0开始的规则
for i in range(1, plots + 1) :
    mu1[i-1] = float(input("Enter the mean for the " + str(i) + " plot :"))
    sigma[i-1] = float(input("Enter the STD for the " + str(i) + " plot :"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 15:45:04