Python - Trying to transfer data between nested lists (IndexError: list assignment index out of range)

Python - Trying to transfer data between nested lists (IndexError: list assignment index out of range)

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

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

你想做的是使用 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