将返回语句作为另一个函数的参数传递

2 投票
1 回答
608 浏览
提问于 2025-04-17 19:01

我看了十个答案,还是找不到我想要的答案,可能我问的问题不对。我想做的是把在fileToDict函数里创建的字典,用作dictValueTotal函数的参数,目的是把字典里的所有值加起来,然后返回这个值(这个值会在第三个函数中用到)。是的,这确实是作业,但我想理解一下,因为我刚学Python,真的不明白怎么把返回值传给另一个函数,网上和我们用的书里都找不到答案。我不想为此创建一个类,因为我们在课堂上还没学到这部分(你看我说的是什么吧?)。提前谢谢你们!

我遇到的错误是:最开始我收到的错误是没有定义全局变量'd',所以我加了这一行:dictionary = fileToDict("words1.txt"),但现在我收到的错误是TypeError: 'builtin_function_or_method' object is not iterable。

差点忘了,我的words1.txt文件长这样,每个字符串/整数在单独一行: the 231049254

cat 120935
hat 910256
free 10141

one 9503490
we 102930
was 20951
#

going 48012
to 1029401
program 10293012
    he 5092309

这是处理这些内容的代码:

import sys

def dictValueTotal (dictionary):
    """dictValueTotal takes in a dictionary and outputs the sum of all the values of the different keys in the input dictionary"""
    valueTotal = sum(dictionary.values)
    return valueTotal


def fileToDict (inFile):
    """takes a name of a file as input and outputs a dictionary containing the contents of that file"""
    fileIn = open(inFile, "r")           #Open a file
    d = {}                           #create a dictionary
    for line in fileIn:
            line = line.strip()          #remove whitespace
            if line == "":               #disregard empty strings
                    continue
            if line[0] == '#':           #disregard lines starting with #
                    continue
            print line                   #debugging purposes
            line = line.split()          #remove duplicated spaces
            print line                   #debugging purposes
            line[1] = int(line[1])
            print line                   #debugging purposes
            key = line[0]
            value = line[1]
            d[key] = value
    print d
    return d
def main():
    fileToDict("words1.txt")
    dictionary = fileToDict("words1.txt")
    dictValueTotal(dictionary)


main()

1 个回答

5

values 是一个方法,你需要去调用它。使用 dictionary.values()(注意要加上括号),而不是 dictionary.values

撰写回答