!
score=[[76,73,85],[88,84,76],[92,82,92],[82,91,85],[72,74,73]]
for i in range(5):
print('student',str(i+1))
for j in range(3):
print(' '+str(j+1)+":",score[i][j])
print(' '+'sum:',score[i][j]+score[i][j]+score[i][j])
print(' '+'avg:',(score[i][j]+score[i][j]+score[i][j])/3)
我打的迴圈印出來sum,avg的答案會跟圖片答案不一樣,想請問要怎麼解決~
問題在
score[i][j]+score[i][j]+score[i][j]
你是 for j 那個迴圈跑完後,才print
這時j停留在最後一個數
所以變成你都是
score[i][2]+score[i][2]+score[i][2]
你可以用sum()
score=[[76,73,85],[88,84,76],[92,82,92],[82,91,85],[72,74,73]]
for i in range(5):
print('student',str(i+1))
for j in range(3):
print(' '+str(j+1)+":",score[i][j])
print(' '+'sum:',sum(score[i]))
print(' '+'avg:',sum(score[i])/3)
至於小數點要取到第幾位,你可以用round()
round(sum(score[i])/3, 2) #取四捨五入到小數點後第2位
score=[[76,73,85],[88,84,76],[92,82,92],[82,91,85],[72,74,73]]
ic = 1
for i in score:
# 用 i 來枚舉 score 就可以了!
print('student',str(ic))
jc = 0
for j in i:
print(' '+str(jc)+":",j)
jc += 1
print(' sum: %d' % (sum(i)))
print(' avg: %d' % (sum(i)/len(i)))
ic += 1
耍個花槍
score=[[76,73,85],[88,84,76],[92,82,92],[82,91,85],[72,74,73]]
ic = 1
for i in score:
# 用 i 來枚舉 score 就可以了!
print('student',str(ic))
jc = 0
for j in i:
print(' 科目%s : %d' % (chr(ord('A')+jc), j))
jc += 1
print(' sum: %d' % (sum(i)))
print(' avg: %d' % (sum(i)/len(i)))
ic += 1
輸出結果
student 1
科目A : 76
科目B : 73
科目C : 85
sum: 234
avg: 78
student 2
科目A : 88
科目B : 84
科目C : 76
sum: 248
avg: 82
..................
謝謝~
忘了平均分數會有小數,可以改成
print(' sum: {0:d}'.format(sum(i)))
print(' avg: {0:.1f}'.format(round(sum(i)/len(i)*10)/10) )
#!/usr/bin/env python3
scores=[[76,73,85],[88,84,76],[92,82,92],[82,91,85],[72,74,73]]
for student, score in enumerate(scores,1):
print("student ", student)
singleSum = sum(score)
singleAvg = round(singleSum / len(score), 2)
for idx, subject in enumerate(score,1):
print(idx, subject)
print("sum:", singleSum)
print("avg:", singleAvg)
最後的總和,總平均那些留給你自己寫.
轉成dict來做。
並且讓計算與顯示分開。
scores=[[76,73,85],[88,84,76],[92,82,92],[82,91,85],[72,74,73]]
def convertToDict(score):
result = dict()
for i, s in enumerate(score):
result[i+1] = s
result["sum"] = sum(score)
result["avg"] = sum(score)/len(score)
return result
scoresDict = [convertToDict(s) for s in scores]
def printScore(index, scoreDict):
print("Student {}".format(index + 1))
for key, value in scoreDict.items():
if key == "avg":
print(" {}: {:.2f}".format(key, value))
else:
print(" {}: {}".format(key, value))
[printScore(i, s) for i, s in enumerate(scoresDict)]
totalSum = sum(s["sum"] for s in scoresDict)
totalAvg = sum(s["avg"] for s in scoresDict) / len(scoresDict)
print("total: {}, avg: {:.2f}".format(totalSum, totalAvg))
highest = max(scoresDict, key=lambda x:x["avg"])
print("highest avg: Student {}: {:.2f}".format(scoresDict.index(highest) + 1, highest["avg"]))