2015-12-10 47 views
-3

如何使用第三個函數調用兩個函數?如何使用第三個函數調用兩個函數?

我想count_authors代碼和authors_counts組合成一個簡單的功能report_author_counts並返回正確的答案顯示出低於

def count_authors(file_name): 
     invert = {} 
     for k, v in load_library(file_name).items(): 
      invert[v] = invert.get(v, 0) + 1 
     return invert 


    def authors_counts(counts, file_name): 
     total_books = 0 
     with open(file_name, 'w') as f: 
      for name, count in counts.items(): 
       f.write('{}: {}\n'.format(name, count)) 
       total_books += int(count) 
      f.write('TOTAL BOOKS: ' + str(total_books)) 



    def report_author_counts(lib_fpath, rep_filepath): 
     counts = count_authors(lib_fpath) 
     authors_counts(counts, rep_filepath) 

我的代碼試圖將它們添加後..invert不是我想要的回報率可達從函數參數除去FILE_NAME因爲自動評估預期兩個參數(lib_fpath,rep_filepath)

def report_author_counts(file_name, lib_fpath, rep_filepath): 
    invert={} 
    counts = {} 
    for k, v in load_library(file_name).items(): 
     invert[v] = invert.get(v, 0) + 1 

    total_books = 0 
    with open(file_name, 'w') as f: 
     for name, count in counts.items(): 
      f.write('{}: {}\n'.format(name, count)) 
      total_books += int(count) 
     f.write('TOTAL BOOKS: ' + str(total_books)) 

     counts = invert(lib_fpath) 
    return (counts, rep_filepath) 

預期輸出

Clarke, Arthur C.: 2 
Herbert, Frank: 2 
Capek, Karel: 1 
Asimov, Isaac: 3 
TOTAL BOOKS: 8 

字典

Foundation|Asimov, Isaac 
Foundation and Empire|Asimov, Isaac 
Second Foundation|Asimov, Isaac 
Dune|Herbert, Frank 
Children of Dune|Herbert, Frank 
RUR|Capek, Karel 
2001: A Space Odyssey|Clarke, Arthur C. 
2010: Odyssey Two|Clarke, Arthur C. 

回答

1

首先,我不會建議你將這些功能,除非你是在一些高性能的環境中工作結合起來。第一個版本比第二個版本更清晰。如果這說的話我認爲你只需在與count_authors相關的代碼中用lib_fpath代替file_name,並且在authors_counts的代碼中用rep_filepath代替countsinvert。就像這樣:

def report_author_counts(lib_fpath, rep_filepath): 
    invert = {} 
    total_books = 0 
    for k, v in load_library(lib_fpath).items(): 
     invert[v] = invert.get(v, 0) + 1 

    with open(rep_filepath, 'w') as f: 
     for name, count in invert.items(): 
      f.write('{}: {}\n'.format(name, count)) 
      total_books += int(count) 
     f.write('TOTAL BOOKS: ' + str(total_books)) 
+0

哪有我回報他們? – loco

+0

你是@erip。 –

+0

@loco'return invert'在底部將返回字典。 'return(invert,total_books)'也會返回書的數量。我不確定你想要返回什麼。 –

0

你的錯誤是在count_authors您使用的是價值,而不是關鍵: 如果我理解正確的話,你的功能應該是這樣的:

def count_authors(file_name): 
    invert = load_library(file_name) 
    for k, v in invert.items(): 
     if not invert.get(k, False): 
      invert[k] = 0 
     return invert 
相關問題