2014-11-06 78 views
0
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除零錯誤除

回答

0
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: 
     try: 
      print(k, len(v), '\t', sum(v)/len(v)) 
    except ZeroDivisionError as detail: 
      print('Handling run-time error:', detail) 

您可以通過try和catch塊捕獲異常ZeroDivisionError;

0

Slartibartfast沒有檔次,從而len(v)是0,當你到他的紀錄。

根據他的「平均」應該是什麼,你可以修改的最後一個循環,是這樣的:

for k, v in dicList: 
    print(k, len(v), '\t', sum(v)/len(v) if len(v)>0 else 'N/A')