计数器似乎没有正确添加

时间:2014-03-12 20:36:16

标签: python

当我测试一个计数器时,我发现它似乎只显示最后一个项目。例如,如果某些东西非常好,它会显示为计数,因此它将是" 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")

2 个答案:

答案 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