2015-12-10 49 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 
相关问题