Python错误:"IndexError:列表索引超出范围" [英] Python error : "IndexError: list index out of range"

查看:58
本文介绍了Python错误:"IndexError:列表索引超出范围"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些数据放入嵌套列表"中.我是初学者,请解释一下,谢谢大家.

I'm trying to put some data to my "nested list". I'm a beginner, please explain me, thank you all.

n_list = []
n = int(input())
for i in range (0,n):
    print(i)
    name = input()
    n_list[i].append(name)
    val = int(input())
    n_list[i].append(val)
print(n_list)

推荐答案

如果要追加到列表,则不需要使用索引(通过使用 n_list [i] 指向数组的第i个元素):

If you're appending to list, you don't need to use index (by using n_list[i] you're pointing to i-th element of the array):

n_list = []
n = int(input())
for i in range (0,n):
    print(i)
    name = input()
    n_list.append(name)
    val = int(input())
    n_list.append(val)
print(n_list)

我要嵌套列表,请执行以下操作:

I you want to nest lists, do this:

n_list = []
n = int(input())
for i in range (0,n):
    print(i)
    inner_list = []
    name = input()
    inner_list.append(name)
    val = int(input())
    inner_list.append(val)
    n_list.append(inner_list)
print(n_list)

这篇关于Python错误:"IndexError:列表索引超出范围"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆