Python:列表索引中的列表超出范围错误

Dan*_*ith 3 python indexing list range

尝试将值附加到列表中的列表时,我收到错误.我究竟做错了什么?

xRange = 4
yRange = 3
baseList = []
values = []
count = 0

#make a list of 100 values
for i in range(100):
    values.append(i)

#add 4 lists to base list
for x in range(xRange):
    baseList.append([])
#at this point i have [[], [], [], []]

#add 3 values to all 4 lists
    for x in range(xRange):
        for y in range(yRange):
            baseList[x][y].append(values[count])
            count += 1

print baseList

#the result i'm expecting is:
#[[0,1,2], [3,4,5], [6,7,8], [9,10,11]]
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

Traceback (most recent call last):
  File "test.py", line 19, in <module>
    baseList[x][y].append(values[count])
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

您不应该索引到一个空列表.你应该append在列表上调用它.

改变这个:

baseList[x][y].append(values[count])
Run Code Online (Sandbox Code Playgroud)

对此:

baseList[x].append(values[count])
Run Code Online (Sandbox Code Playgroud)

结果:

[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
Run Code Online (Sandbox Code Playgroud)

看到它在线工作:ideone