Iterate through/compare values in arrays and print string based on result, IndexError: out of bounds
Iterate through/compare values in arrays and print string based on result, IndexError: out of bounds
正在尝试根据团队分数创建 win/loss/tie 列表。我的尝试:
#import numpy
import numpy as np
#create array for week numbers
week_number = np.array(['Week 1','Week 2','Week 3','Week 4','Week 5','Week 6'])
#create arrays for scores
my_team_score = np.array([41,17,28,21,10,18])
opposing_team_score = np.array([33,11,30,28,17,30])
#create iteration to check win, tie, or loss and print result
for i in my_team_score:
if my_team_score[i] > opposing_team_score[i]:
print(week_number[i] + ': Win')
elif my_team_score[i] == opposing_team_score[i]:
print(week_number[i] + ': Tie')
else:
print(week_number[i] + ': Loss')
接收错误:
IndexError: index 41 is out of bounds for axis 0 with size 6
当迭代一个可迭代对象时,你拥有的是一个值本身,而不是一个索引。这里 i
将在每次迭代时取值 41, 17, 28, 21, 10, 18
。
要获取索引,您将使用 for i in range(len(my_team_score)):
但使用 zip
以获得更好的代码
for a_score, b_score, week in zip(my_team_score, opposing_team_score, week_number):
if a_score > b_score:
print(week + ': Win')
elif a_score == b_score:
print(week + ': Tie')
else:
print(week + ': Loss')
正在尝试根据团队分数创建 win/loss/tie 列表。我的尝试:
#import numpy
import numpy as np
#create array for week numbers
week_number = np.array(['Week 1','Week 2','Week 3','Week 4','Week 5','Week 6'])
#create arrays for scores
my_team_score = np.array([41,17,28,21,10,18])
opposing_team_score = np.array([33,11,30,28,17,30])
#create iteration to check win, tie, or loss and print result
for i in my_team_score:
if my_team_score[i] > opposing_team_score[i]:
print(week_number[i] + ': Win')
elif my_team_score[i] == opposing_team_score[i]:
print(week_number[i] + ': Tie')
else:
print(week_number[i] + ': Loss')
接收错误:
IndexError: index 41 is out of bounds for axis 0 with size 6
当迭代一个可迭代对象时,你拥有的是一个值本身,而不是一个索引。这里 i
将在每次迭代时取值 41, 17, 28, 21, 10, 18
。
要获取索引,您将使用 for i in range(len(my_team_score)):
但使用 zip
以获得更好的代码
for a_score, b_score, week in zip(my_team_score, opposing_team_score, week_number):
if a_score > b_score:
print(week + ': Win')
elif a_score == b_score:
print(week + ': Tie')
else:
print(week + ': Loss')