当我测试一个计数器时,我发现它似乎只显示最后一个项目。例如,如果某些东西非常好,它会显示为计数,因此它将是" 1"。但是无论其他数据如何,其余数据都是0。
def mealrating(score, review):
for x in range(0,len(score)):
mp = 0
mg = 0
me = 0
if score[x] >= 1 and score[x] <= 3:
review.append("poor")
mp = mp + 1
if score[x] >= 4 and score[x] <= 6:
review.append("good")
mg = mg + 1
if score[x] >= 7 and score[x] <= 10:
review.append("excellent")
me = me + 1
print("The customer rated tonight's meal as:")
print('Poor:' + str(mp))
print('Good:' + str(mg))
print('Excellent:' + str(me))
print("\n")
答案 0 :(得分:2)
您在每次迭代中重置mp,mg和me。
def mealrating(score, review):
mp = 0
mg = 0
me = 0
for x in range(0,len(score)):
if score[x] >= 1 and score[x] <= 3:
review.append("poor")
mp = mp + 1
if score[x] >= 4 and score[x] <= 6:
review.append("good")
mg = mg + 1
if score[x] >= 7 and score[x] <= 10:
review.append("excellent")
me = me + 1
print("The customer rated tonight's meal as:")
print('Poor:' + str(mp))
print('Good:' + str(mg))
print('Excellent:' + str(me))
print("\n")
答案 1 :(得分:1)
您必须初始化循环外的计数器:
mp = 0
mg = 0
me = 0
for x in range(0, len(score)):
# same as before
否则他们会在每次迭代时重置!为了使您的代码更像Pythonic,请考虑以下提示:
x >= i and x <= j
的条件可以更简洁地写为i <= x <= j
elif
+=
增加变量这就是我的意思:
mp = mg = me = 0
for s in score:
if 1 <= s <= 3:
review.append("poor")
mp += 1
elif 4 <= s <= 6:
# and so on