我必須創建一個函式,該函式將包含不同回合分數的字典作為引數。該函式回傳所有輪次的平均分數。
這是該函式應如何作業的示例:
>>> find_average({'round 1': [1, 2, 3, 4], 'round 2': [3, 4, 2, 7], 'round 3': [2, 7, 5, 6]})
4.8
我試過這個:
def find_average(dictionary):
average = sum(dictionary.values())/len(dictionary)
return average
但我收到一個錯誤:
TypeError: unsupported operand type(s) for : 'int' and 'list'
我應該怎么辦?
uj5u.com熱心網友回復:
您需要找到字典中每個值的平均值并找到該串列的平均值。
def find_average(dictionary):
sums = [sum(lst)/len(lst) for lst in dictionary.values()]
return sum(sums)/len(sums)
結果將是3.8333333333333335,但您可以像這樣對結果進行四舍五入,round(sum(sums)/len(sums), 1)這給了您3.8
uj5u.com熱心網友回復:
利用itertools.chain
from itertools import chain
d = {'round 1': [1, 2, 3, 4], 'round 2': [3, 4, 2, 7], 'round 3': [2, 7, 5, 6]}
sum(chain(*d.values()))/len(list(chain(*d.values())))
#output : 3.8333333333333335
uj5u.com熱心網友回復:
您將字典值相加,每個值都是一個串列,然后除以不正確的鍵長度。
print(sum(dictionary.values()))
"""
Traceback (most recent call last):
File "/tmp/main.py", line 2, in <module>
import user_code
File "/tmp/user_code.py", line 11, in <module>
print(find_average({'round 1': [1, 2, 3, 4], 'round 2': [3, 4, 2, 7], 'round 3': [2, 7, 5, 6]}))
File "/tmp/user_code.py", line 6, in find_average
print(sum(dictionary.values()))
TypeError: unsupported operand type(s) for : 'int' and 'list'
"""
前面的代碼失敗的原因sum是對串列進行操作,而 不是對串列進行操作。
以下運行回傳正確答案:
def find_average(dictionary):
s = 0
c = 0
for i in dictionary.values():
s = sum(list(i))
c = len(list(i))
return s/c;
find_average({'round 1': [1, 2, 3, 4], 'round 2': [3, 4, 2, 7], 'round 3': [2, 7, 5, 6]})) # 3.8333333333333335
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528187.html
標籤:Python字典
上一篇:查找總和為6的字典鍵
下一篇:訪問串列中多個字典的值
