这是我的代码:
def SetUpScores():
scoreBoard= []
names = ["George", "Paul", "John", "Ringo", "Bryan"]
userScores = [17, 19, 23, 25, 35]
for i in range(0,5):
scoreBoard.append([])
for j in range(0,2):
scoreBoard[i].append(names[i])
scoreBoard[i][1]= userScores[i]
我基本上试图创建一个包含名称和userScore的二维数组,我已经看了很多,到目前为止我一直得到列表赋值索引的错误超出范围或'list'无法调用。
如果我从我的代码中删除最后一行,即:
def SetUpScores():
scoreBoard= []
names = ["George", "Paul", "John", "Ringo", "Bryan"]
userScores = [17, 19, 23, 25, 35]
for i in range(0,5):
scoreBoard.append([])
for j in range(0,2):
scoreBoard[i].append(names[i])
我得到了
[['George','George'],['Paul','Paul'],['John','John'],['Ringo','Ringo'],['Bryan',' Bryan']]没有任何错误(这只是为了测试是否制作了数组)。
我想做类似的事情:
[['George',17],['Paul',19],['John',23],['Ringo',25],['Bryan',35]]
任何帮助将不胜感激,谢谢!
答案 0 :(得分:2)
使用行scoreBoard[i].append(names[i])
,您可以添加单个元素,而不是列表。因此,下一行scoreBoard[i][1]= userScores[i]
会导致错误,因为它引用了names[i]
的第二个元素,它只是一个字符串。
做你想做的最紧凑的方式是
for name, score in zip(names, userScores):
scoreBoard.append([name, score])
答案 1 :(得分:1)
names = ["George", "Paul", "John", "Ringo", "Bryan"]
userScores = [17, 19, 23, 25, 35]
L3 =[]
for i in range(0, len(L1)):
L3.append([L1[i], L2[i]])
print(L3)
Output:
[[17, 'George'], [19, 'Paul'], [23, 'John'], [25, 'Ringo'], [35, 'Bryan']]