简体   繁体   English

2D数组以及如何使用一维数组填充它们

[英]2d arrays and how to populate them with one dimensional arrays

This is my code: 这是我的代码:

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]

I'm basically trying to create a two dimensional array that holds the name and the userScore, I have looked this up alot and so far I keep getting the error of list assignment index out of range or 'list' cannot be called. 我基本上是在尝试创建一个包含名称和userScore的二维数组,我对此进行了很多查找,到目前为止,我一直在使列表分配索引的错误超出范围,或者无法调用“列表”。

If i remove the last line from my code ie: 如果我从代码中删除最后一行,即:

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])

I get 我懂了

[['George', 'George'], ['Paul', 'Paul'], ['John', 'John'], ['Ringo', 'Ringo'], ['Bryan', 'Bryan']] without any errors (this is just to test if the array was made). [['George','George'],['Paul','Paul'],['John','John'],['Ringo','Ringo'],['Bryan','Bryan'] ]而没有任何错误(这只是为了测试是否制作了数组)。

I would like to make something like: 我想做些类似的事情:

[['George', 17], ['Paul', 19], ['John', 23], ['Ringo', 25], ['Bryan', 35]] [['George',17],['Paul',19],['John',23],['Ringo',25],['Bryan',35]]

Any help would be appreciated, thank you! 任何帮助,将不胜感激,谢谢!

With the line scoreBoard[i].append(names[i]) , you add a single element, not a list. 使用scoreBoard[i].append(names[i]) ,您可以添加单个元素,而不是列表。 So, the next line scoreBoard[i][1]= userScores[i] causes an error, because it refers to the second element of names[i] , which is just a string. 因此,下一行scoreBoard[i][1]= userScores[i]会导致错误,因为它引用了names[i]的第二个元素,它只是一个字符串。

The most compact way to do what you want would be 做您想做的最紧凑的方法是

for name, score in zip(names, userScores):
    scoreBoard.append([name, score])
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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM