亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在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 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號