-1

我正在编写一个代码来查找平均家庭收入,以及有多少家庭处于贫困线以下。

这是我到目前为止的代码

def povertyLevel():

inFile = open('program10.txt', 'r')
outFile = open('program10-out.txt', 'w')

outFile.write(str("%12s  %12s %15s\n" % ("Account #", "Income", "Members")))

lineRead = inFile.readline()       # Read first record
while lineRead != '':              # While there are more records

   words = lineRead.split()        # Split the records into substrings
   acctNum = int(words[0])         # Convert first substring to integer
   annualIncome = float(words[1])  # Convert second substring to float
   members = int(words[2])         # Convert third substring to integer

   outFile.write(str("%10d  %15.2f  %10d\n" % (acctNum, annualIncome, members)))

   lineRead = inFile.readline()    # Read next record


# Close the file.
inFile.close() # Close file

调用主函数。

贫困水平()

我试图找到年收入的平均值,而我试图做的是

avgIncome = (sum(annualIncome)/len(annualIncome)) outFile.write(avgIncome)

我在 while lineRead 中做到了这一点。但是它给了我一个错误说

avgIncome = (sum(annualIncome)/len(annualIncome)) TypeError: 'float' object is not iterable

目前我正在寻找超过平均收入的家庭。

4

2 回答 2

4

avgIncome需要一个序列(例如 a list)(感谢您的更正,Magenta Nova。),但它的参数annualIncome是 a float

annualIncome = float(words[1])

在我看来,您想建立一个列表:

allIncomes = []
while lineRead != '':
    ...
    allIncomes.append(annualIncome)

averageInc = avgIncome(allIncomes)

(请注意,我的avgIncome通话缩进级别少了一个。)

此外,一旦你完成这项工作,我强烈建议您访问https://codereview.stackexchange.com/。你可以得到很多关于如何改进这一点的反馈。

编辑:

鉴于您的编辑,我的建议仍然有效。在进行比较之前,您需要计算平均值。获得平均值后,您将需要再次循环数据以比较每个收入。注意:我建议以某种方式为第二个循环保存数据,而不是重新解析文件。(您甚至可能希望将读取数据与完全计算平均值分开。)这可能最好使用新对象或 anamedtuple或 a来完成dict

于 2014-12-03T02:46:28.540 回答
2

sum() 和 len() 都将iterable作为参数。阅读 python 文档以获取有关可迭代的更多信息。您将浮点数作为参数传递给它们。获得浮点数的总和或长度意味着什么?即使在编码世界之外思考,也很难理解这一点。

看来您需要复习 python 类型的基础知识。

于 2014-12-03T02:47:41.313 回答