我知道索引时超出范围意味着什么,但是我很难理解为什么我的代码会产生这个错误
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),因此出现错误。您试图使用索引访问其中的元素,但没有索引。下面是一个简单的例子:
您要做的是使用
append()
:相关问题 更多 >
编程相关推荐