为了账号安全,请及时绑定邮箱和手机立即绑定

在Python中创建一个for循环来检查列表值

在Python中创建一个for循环来检查列表值

阿晨1998 2023-08-03 17:16:16
我的家庭作业有问题。我需要创建一个 for 循环来计算某个值在列表中出现的次数。这是代码:def get_test_scores():    tests = []    for i in range(SIZE):        test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))        while (test_score <0) or (test_score >100):            print("ERROR!")            test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))            tests.append(test_score)        return testsdef find_perfect(tests):    count = 0    for test_score in tests:        if test_score == 100:            count += 1    return count我无法获得计数值来反映我输入了多少个 100
查看完整描述

3 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

当您处理此类事情(无论是作业还是生产代码)时,最好测试每个单独的函数以确保它们正常工作。例如,尝试find_perfect使用不同的(硬编码的)列表运行;你会发现它每次都能得到正确的答案。现在尝试测试get_test_scores并打印输出。哎呀!

您的问题是您仅附加最后的测试分数。该线tests.append(test_score)应该位于for循环内部。


查看完整回答
反对 回复 2023-08-03
?
紫衣仙女

TA贡献1839条经验 获得超15个赞

你tests.append(test_score)会发生一次,因为它在 for 循环之外,试试这个:


def get_test_scores():

    tests = []

    for i in range(SIZE):

        test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))

        while (test_score <0) or (test_score >100):

            print("ERROR!")

            test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))        

        tests.append(test_score)    

    return tests

顺便说一句,我认为值得快速计算你有多少个 100 并且不再迭代,在 python 中,你可以从像 tuple 这样的函数返回很少的值,例如:


def get_test_scores():

    tests = []

    count = 0

    for i in range(SIZE):

        test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))

        while (test_score <0) or (test_score >100):

            print("ERROR!")

            test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))

        if test_score == 100:

            count += 1

        tests.append(test_score)    

    return count, tests

用法 :


count, scores = get_test_scores()

count 是一个数字,scores 是分数列表


查看完整回答
反对 回复 2023-08-03
?
DIEA

TA贡献1820条经验 获得超2个赞

tests.append(test_score)通过在 for 循环之前添加 tab 来使其内部



查看完整回答
反对 回复 2023-08-03
  • 3 回答
  • 0 关注
  • 86 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信