iT邦幫忙

2

python 成績計算問題

  • 分享至 

  • xImage

https://ithelp.ithome.com.tw/upload/images/20200622/20127646qNpJBxEZow.png!
https://ithelp.ithome.com.tw/upload/images/20200622/20127646QIitwoppcV.png

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的答案會跟圖片答案不一樣,想請問要怎麼解決~

你放的地方執行永遠會是 [i][2]
這樣應該知道怎麼解決了
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
2
powerc
iT邦研究生 5 級 ‧ 2020-06-22 14:03:54
最佳解答

問題在

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位

謝謝!

可以請問打sum(score[i])是指計算那一行成績的總和嗎?

1
japhenchen
iT邦超人 1 級 ‧ 2020-06-22 13:55:40
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 
看更多先前的回應...收起先前的回應...

剛出了小差錯,format用法不正確,改正了

耍個花槍

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)  )

1
一級屠豬士
iT邦大師 1 級 ‧ 2020-06-22 14:22:06
#!/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)

https://ithelp.ithome.com.tw/upload/images/20200622/200506476QupXUF5Q8.png

最後的總和,總平均那些留給你自己寫.

謝謝~

2
froce
iT邦大師 1 級 ‧ 2020-06-22 21:02:21

轉成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"]))

我要發表回答

立即登入回答