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

Python-尝试在嵌套列表之间传输数据(索引器错误:列表分配索引超出范围),python,list,range,out,index-error,Python,List,Range,Out,Index Error,我知道索引时超出范围意味着什么,但我很难理解为什么我的代码会产生这个错误 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)

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

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 

由于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

a、b、c等是字符串还是变量?如果是后者,则还需要定义它们,否则此代码会因另一个错误而失败。此外,并非所有嵌套列表都用逗号分隔。它们是字符串。我将对代码进行编辑以使其更加清晰。与您的问题无关,但请查看使用情况。
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