计数器似乎添加不正确

2024-06-16 10:47:03 发布

您现在位置: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")

Tags: and数据项目ifdef计数器mpreview
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")

必须在循环外初始化计数器:

mp = 0
mg = 0
me = 0
for x in range(0, len(score)):
    # same as before

否则每次迭代都会被重置!要使代码更具python风格,请考虑以下提示:

  • 形式为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

相关问题 更多 >