python - 索引错误: list index out of range: I can uderstand why this error happens

标签 python django excel

我收到错误 IndexError:列表索引超出范围。 我想将字典数据放入 model(User) 中。 我写的

book2 = xlrd.open_workbook('./data/excel1.xlsx')
sheet2 = book2.sheet_by_index(0)
for row_index in range(1,sheet2.nrows):
    rows = sheet2.row_values(row_index)
    print(rows)
    user3 = User.objects.filter(user_id=rows[0])
    if user3:
        user3.update(talk1=rows[2],characteristic1=rows[3],talk2=rows[4],characteristic2=rows[5],
                     talk3=rows[6], characteristic3=rows[7],talk4=rows[8], characteristic4=rows[9],
                     talk5=rows[10], characteristic5=rows[11],talk6=rows[12], characteristic6=rows[13],
                     talk7=rows[14], characteristic7=rows[15], talk8=rows[16], characteristic8=rows[17])

但是,每个列表的行索引数不同。行数就像

['001200cd3eF', 'Tom', 'Hi', 'greeting', 'Goodmorning', 'greeting', 'Bye' 'say good‐bye', '', '', '']['007700ab7Ws', 'Blear', 'How are you', 'greeting', 'Thx', 'Thanks', '', '', '']

所以每个列表的索引数是不同的,最大索引是13。 models.py 是

Class User(models.Model):
    talk1 = models.CharField(max_length=500,null=True)
    talk2 = models.CharField(max_length=500, null=True)
    talk3 = models.CharField(max_length=500, null=True)
    talk4 = models.CharField(max_length=500, null=True)
    talk5 = models.CharField(max_length=500, null=True)
    talk6 = models.CharField(max_length=500, null=True)
    talk7 = models.CharField(max_length=500, null=True)
    talk8 = models.CharField(max_length=500, null=True)
    characteristic1 = models.CharField(max_length=500,null=True)
    characteristic2 = models.CharField(max_length=500, null=True)
    characteristic3 = models.CharField(max_length=500, null=True)
    characteristic4 = models.CharField(max_length=500, null=True)
    characteristic5 = models.CharField(max_length=500, null=True)
    characteristic6 = models.CharField(max_length=500, null=True)
    characteristic7 = models.CharField(max_length=500, null=True)
    characteristic8 = models.CharField(max_length=500, null=True)

如果列表没有值,我想将其设置为 null。我应该如何解决这个问题?我应该写什么?

最佳答案

您好,可以处理类似列表超出索引错误,您可以添加带有空值的额外索引

rows=sheet2.row_values(row_index)
append_empty  = ['','','','',''] #here mention how many empty index as you need
rows = rows + append_empty
#goes to your update logic

关于python - 索引错误: list index out of range: I can uderstand why this error happens,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46166806/

相关文章:

python - 连接并覆盖同一数据框中的属性

python - 使用 babel、django 和 jinja2 提供 i18n js 服务

javascript - DataTables - 如何使用我自己的按钮进行导出?

python - AUTH_USER_MODEL 指的是尚未安装和创建的模型 .. AbstractUser 模型无法登录

itertools.product 的 python 输入

django - 使用 create-react-app 自定义静态文件路径?

arrays - 表排序和查找

vba - 在excel vba中为特定范围设置自定义数字格式时键入不匹配错误

python - python中的列表理解中只有正数

python - Django def __str__ 列表索引超出范围