def getSortedKeyList(dl):
kl = list(dl.items())
kl.sort()
return kl
def tupleListToDict(a):
b = {}
for k, v in a:
b[k] = b.get(k, [])+v
return b
def main():
gradeList = [('Zaphod', [33, 20]), ('Zaphod', [75, 48]), \
('Slartibartfast', []), ('Trillian', [98, 88]), \
('Trillian', [97, 77]), ('Slartibartfast', []), \
('Marvin', [2000, 500]), ('Authur', [42, 20]), \
('Authur', [64]), ('Trillian', [99]), \
('Marvin', [450]), ('Marvin', [550]), \
('Agrajag', []), ('Agrajag', []), ('Agrajag', [0]), \
('Ford', [50]), ('Ford', [50]), ('Ford', [50])]
print('\t', '\t', "Grade", '\t')
print('\t', "Name", '\t', "Count", '\t', "Average")
print("-----------------------------------------")
dicList = tupleListToDict(gradeList)
dicList = getSortedKeyList(dicList)
for k, v in dicList:
print(k, len(v), '\t', sum(v)/len(v))
我想從字典中創建一個表。首先,我將元組轉換爲字典並按鍵對字典進行排序。接下來,我試圖打印出(密鑰,密鑰數量,平均值)。但是,當我嘗試對平均部分進行求和(v)/ len(v)時,我得到了除零誤差。爲了避免這個錯誤,我嘗試將字典中的空值返回到0,但我不知道如何去做。請幫忙。字典python除零錯誤除