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

3

当我尝试将值添加到列表中的另一个列表时,出现了错误。我做错了什么?

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]]

I'm getting this error:

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

顺便提一下,你可以这样创建一个包含n个空列表的列表:baseList = [[]] * n。不需要显式循环。 - Iguananaut
1
@Iguananaut - 这将创建对同一列表的多个引用,因此当您修改其中一个时,所有引用都会受到影响。这是一个常见的错误。 - TigerhawkT3
啊,绝对的。好尴尬! - Iguananaut
2个回答

5

不应该对空列表进行索引操作。应该在列表本身上调用append方法。

将此代码更改为:

baseList[x][y].append(values[count])

变为这样:

baseList[x].append(values[count])

结果:

[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]

请查看在线演示:ideone

1
for x in range(xRange):
    baseList.append([])
# at this point i have [[], [], [], []]

没错,baseList = [[], [], [], []]。因此,访问 baseList[0][0] 将失败,因为第一个子列表没有元素。

顺便说一句,你可以使用一些itertoolsrecipes更轻松地获得所需的列表。

>>> x = 4
>>> y = 3
>>> list(itertools.islice(zip(*([itertools.count()] * y)), x))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]

这基本上是一个从0开始的不定数量的y-分组器的x-


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接