如何用第三个函数调用两个函数?

时间:2015-12-10 23:08:16

标签: python

如何用第三个函数调用两个函数?

我想将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.

2 个答案:

答案 0 :(得分:1)

首先,除非您在某些高性能环境中运行,否则我不建议您将这些功能组合在一起。第一个版本比第二个版本更清晰。说完后我认为您必须在与file_name相关的代码中将lib_fpath替换为count_authors,并在与{{1相关的代码中使用rep_filepath替换authors_countscounts替换invert。像这样:

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))

答案 1 :(得分: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