直截了當,我有一個任務,我需要將字典資料列印為表格,每個水平值的間距為“10”。列印出名字和姓氏很簡單,但是如何將每個等級(數學、ProgVal、體育)分開?到目前為止,我的代碼僅垂直列印出所有成績。請注意,成績不是整數/浮點數,但我無法更改它,因為任務是編輯現有代碼并且該代碼已經存在。希望你能幫忙。(我是 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 printGrades():
print("list of students:")
print("{:10} {:10} {:10} {:10} {:10}".format('first', 'last', 'Math', 'ProgVal', 'Sports'))
for lName, fName in students.keys():
studentRecord = students[(lName, fName)]
for course in studentRecord:
print(studentRecord[course])
while True:
print()
command = input("command:> ")
command = command.lower()
if command == 'print':
printGrades()
elif command == 'done':
break
print("DONE")
輸出:
command:> print
list of students:
first last Math ProgVal Sports
10
5
5
7
3
6
3
7
7
10
10
3
command:>
uj5u.com熱心網友回復:
您的代碼格式化標題。但它不會格式化資料。
print("{:10} {:10} {Math:10} {ProgVal:10} {Sports:10}".format(lname, fname, **studentRecord))
您可能希望使用:>10而不是右對齊數字:10。
uj5u.com熱心網友回復:
試試這個為你的功能:
def printGrades():
print("list of students:")
print(
"{:10} {:10} {:10} {:10} {:10}".format(
"first", "last", "Math", "ProgVal", "Sports"
)
)
for key in students:
values = students[key]
print("{:10} {:10} {:10} {:10} {:10}".format(key[0], key[1], values["Math"], values["ProgVal"], values["Sports"]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/334659.html
