Python正在尝试在嵌套列表之间传输数据(IndexError:列表分配索引超出范围)

2024-04-26 06:13:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道索引时超出范围意味着什么,但是我很难理解为什么我的代码会产生这个错误

import random


howMany = random.randint(1,3)
oldList = [['a',1,2,3], ['b',1,2,3], ['c',1,2,3], ['d',1,2,3], ['e',1,2,3], ['f',1,2,3], ['g',1,2,3], ['h',1,2,3], ['i',1,2,3]]
newList = []
for i in range(0, howMany): 
    newList[i] = oldList[random.randint(0, len(oldList)-1)] # subtract one 

Tags: 代码inimportforlen错误rangerandom
1条回答
网友
1楼 · 发布于 2024-04-26 06:13:07

由于newList为空(长度为0),因此出现错误。您试图使用索引访问其中的元素,但没有索引。下面是一个简单的例子:

>>> newList = []
>>> i = 0
>>> newList[i] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

您要做的是使用append()

import random


howMany = random.randint(1,3)
oldList = [['a',1,2,3], ['b',1,2,3], ['c',1,2,3], ['d',1,2,3], ['e',1,2,3], ['f',1,2,3], ['g',1,2,3], ['h',1,2,3], ['i',1,2,3]]
newList = []
for i in range(0,howMany): 
    newList.append(oldList[random.randint(0, len(oldList)-1)]) # subtract one 

相关问题 更多 >