所以我想使用串列作為鍵來參考字典。
import random
gradePoints = {"A":4,"B":3,"C":2,"D":1,"F":0}
courseList = ["CST 161","Mat 144","ENG 201","PSY 101","HIS 101"]
gradeList = ["A","B","C","D","F"]
creditList = [3,4]
totalCredits=0
qualityPoints=0
print("Course..Grade..Value Per Course")
for i in range(0,len(courseList)):
print(courseList[i]," ",end='')
gPoints=random.randint(0,len(gradePoints))
creditHours=random.randint(0,len(creditList))
valuePerCourse= (gPoints*creditHours)
totalCredits=creditHours
qualityPoints=valuePerCourse
print(gPoints)
gpa=qualityPoints/totalCredits
print("GPA is: ", round(gpa,2))
我嘗試使用嵌套回圈來包含字母,而所發生的只是結果到處都是,而不是列印在 courseList 旁邊,而是列印在下一行,讓它看起來很討厭。我的期望是在 courseList 旁邊列印gradeList,旁邊是gradePoint,具體取決于從gradeList 中提取的內容
Course..Grade..Value Per Course
CST 161 2
Mat 144 2
ENG 201 2
PSY 101 2
HIS 101 2
GPA is: 2.0
這就是我得到的,它的意思是隨機的
Course..Grade..Value per course
CST 161 A 4
ENG 101 B 3
MAT 119 B 4
像這樣的東西就是我想要的
我打算寫一個程式來接受這個字典gradePoints = {"A":4,"B":3,"C":2,"D":1,"F":0}
這個串列:
courseList = ["CST 161","Mat 144","ENG 201","PSY 101","HIS 101"]
并隨機使用每個串列中的元素:
等級串列 = ["A","B","C","D","F"]
信用串列 = [3,4]
并產生一個平均績點。
GradeList 元素將作為參考成績點的鍵嵌入。
(例如 gPoints =gradePoints[隨機等級串列元素])
(例如 creditHours = 隨機 creditList 元素)。
要獲取隨機串列元素,請使用范圍為 (0,len(list)) 的 randint 方法。
這將乘以每門課程的 gPoints。
將它們相乘以獲得該課程的 valuePerCourse。
(例如 valuePerCourse = (creditHours * gPoints),這將產生該課程的價值。
對于每門課程(每次通過回圈),
將 creditHours 添加到 totalCredits 和
將 valuePerCourse 添加到 qualityPoints
qualityPoints 除以總學分得出 GPA。
顯示每門課程的成績和每門課程的價值。
顯示質量點和 GPA。
顯示將識別您的輸出的正確字串文字。
uj5u.com熱心網友回復:
嘗試:
import random
gradePoints = {"A":4,"B":3,"C":2,"D":1,"F":0}
courseList = ["CST 161","Mat 144","ENG 201","PSY 101","HIS 101"]
gradeList = ["A","B","C","D","F"]
creditList = [3,4]
totalCredits=0
qualityPoints=0
print("Course..Grade..Value Per Course")
gpa = 0
for i in range(0,len(courseList)):
print(courseList[i]," ",end='')
gPoints=random.randint(0,len(gradePoints)-1) # <<<
creditHours=creditList[random.randint(0,len(creditList)-1)] # <<<
valuePerCourse= (gPoints*creditHours)
totalCredits=creditHours
qualityPoints=valuePerCourse
print(list(reversed(gradeList))[gPoints], ' ', gPoints) # <<<
gpa = qualityPoints/totalCredits # <<<
print(" GPA is: ", round(gpa, 2)) # <<<
更改的行標有# <<<
給出:
Course..Grade..Value Per Course
CST 161 F 0
Mat 144 D 1
ENG 201 A 4
PSY 101 F 0
HIS 101 F 0
GPA is: 5.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/530236.html
標籤:Python列表循环字典
