gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:51 24 4
gpt4 key购买 nike

尝试将值附加到列表内部的列表时出现错误。我做错了什么?

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

我收到这个错误:

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

最佳答案

你不应该索引一个空列表。您应该在列表本身上调用 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

关于Python:列表中的列表索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13692751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com