python追加到嵌套列表,索引超出范围

时间:2019-04-03 09:50:48

标签: python list nested

我正在尝试创建一个嵌套列表。结果将类似于puts,我尝试了以下操作,但索引超出范围错误:

[[0,1],[2,3],[0,4]]

不是将0附加到列表的第一项吗?我应该怎么做?非常感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

有一些错字,你应该做:

list = [[]]
list[0].append(0)

您需要先拥有第一个元素...

编辑:

使用:

list = []
for i in range(3):
    list.append([])
    list[-1].append(0)

答案 1 :(得分:1)

为此,您需要首先将list附加到list,即:

list = []
list.append([])
list[0].append(0)
print(list)
# [[0]]

答案 2 :(得分:0)

lst = []
lst.append([0,1])
lst.append([2,3])
lst.append([0,4])
print(lst)

如何?还是您需要循环使用一组恒定的数字?