在編程課程中,我現在正在使用 python 的字典點。所以我有這個任務,我需要添加一個“失敗”命令,如果成績低于 4,它基本上是列印出學生。我用谷歌搜索并在這里搜索了類似的問題,但找不到類似的例子。希望您能夠幫助我。另外,我已經添加了代碼,在“def fail():”中你可以看到我的想法。但是這里有一個錯誤代碼 - ValueError: too many values to unpack (expected 2)。PS,我是python的新手。
students = {('Ozols', 'Jānis'): {'Math': '10', 'ProgVal': '5', 'Sports': '5'},
('Krumi?a', 'Ilze'): {'Math': '7', 'ProgVal': '3', 'Sports': '6'},
('Liepa', 'Peteris'): {'Math': '3', 'ProgVal': '7', 'Sports': '7'},
('Lapsa', 'Maris'): {'Math': '10', 'ProgVal': '10', 'Sports': '3'}}
courses = ['Math', 'ProgVal', 'Sports']
def fail():
for lName, fName in students.keys():
for course, grade in students.values():
if grade < 4:
print(fName, lName)
while True:
print()
command = input("command:> ")
command = command.lower()
if command == 'fail':
fail()
elif command == 'done':
break
print("DONE")
uj5u.com熱心網友回復:
試試下面的
students = {
('Ozols', 'Jānis'): {
'Math': '10',
'ProgVal': '5',
'Sports': '5'
},
('Krumi?a', 'Ilze'): {
'Math': '7',
'ProgVal': '3',
'Sports': '6'
},
('Liepa', 'Peteris'): {
'Math': '3',
'ProgVal': '7',
'Sports': '7'
},
('Lapsa', 'Maris'): {
'Math': '10',
'ProgVal': '10',
'Sports': '3'
}
}
courses = ['Math', 'ProgVal', 'Sports']
def fail():
for k,v in students.items():
for course, grade in v.items():
if int(grade) < 4:
print(f'{k[0]} {k[1]} failed in {course}')
fail()
輸出
Krumi?a Ilze failed in ProgVal
Liepa Peteris failed in Math
Lapsa Maris failed in Sports
uj5u.com熱心網友回復:
您的代碼存在一些問題。
首先,您應該使用整數 (int) 或浮點數來存盤學生的分數。您可以通過將它們更改為整數來修復它:
students = {('Ozols', 'Jānis'): {'Math': 10, 'ProgVal': 5, 'Sports': 5},
('Krumi?a', 'Ilze'): {'Math': 7, 'ProgVal': 3, 'Sports': 6},
('Liepa', 'Peteris'): {'Math': 3, 'ProgVal': 7, 'Sports': 7},
('Lapsa', 'Maris'): {'Math': 10, 'ProgVal': 10, 'Sports': 3}}
其次,您不應該students.values()在 of回圈中使用回圈,students.keys()因為它會再次回圈遍歷整個字典 - 您希望回圈遍歷每個 student的值(它們是分數字典)的每個主題,這些值存盤在名單稱為.students
嘗試這個:
students = {('Ozols', 'Jānis'): {'Math': 10, 'ProgVal': 5, 'Sports': 5},
('Krumi?a', 'Ilze'): {'Math': 7, 'ProgVal': 3, 'Sports': 6},
('Liepa', 'Peteris'): {'Math': 3, 'ProgVal': 7, 'Sports': 7},
('Lapsa', 'Maris'): {'Math': 10, 'ProgVal': 10, 'Sports': 3}}
courses = ['Math', 'ProgVal', 'Sports']
for lName, fName in students.keys():
studentRecord = students[(lName, fName)]
for course in studentRecord:
if studentRecord[course] < 4:
print(fName, lName, course)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/334660.html
上一篇:將字典格式化為表格
