【问题标题】:Finding Sum and Average of Floating-Point Numbers from File (python 3.5)从文件中查找浮点数的总和和平均值(python 3.5)
【发布时间】:2016-09-28 13:17:16
【问题描述】:

我正在编写一个程序,它允许用户打开文件并解析文本以获得垃圾邮件的可信度。我已经能够创建这个循环,但我现在需要创建所有这些数字的总和,这样我才能找到平均值。由于数字不是整数,因此我无法使用我见过的其他解决方案。浮点数的一些示例是:垃圾邮件:0.7605、0.6932、0.7558、0.6526。该程序需要能够读取两个不同的文件,因此我无法创建列表。

这是我现在拥有的:

sum = 0
average=0
total=0

fname = input('Enter the file name: ')
fhand = open(fname)
count=0
for line in fhand:
    if line.startswith("X-DSPAM-Confidence: ") :
        spam = line[19:].strip()
        spam = float (spam)
        print('Spam:', spam)
        count = count + 1

sum(float(item) for item in spam)

average= total/ count
print('Average: ', average)

它正在打破 sum(float(item) 垃圾邮件中的项目)

【问题讨论】:

    标签: floating-point sum average python-3.5


    【解决方案1】:

    那是因为您将 spam 视为 sum 函数中的列表。

    您可以像这样附加到垃圾邮件列表:

    for line in fhand:
        if line.startswith("X-DSPAM-Confidence: ") :
            temp = line[19:].strip()
            spam.append(float (temp))
            print('Spam:', spam)
            # count is not needed if spam is a list count = len(spam)
            count = count + 1
    
    sum(float(item) for item in spam)
    

    或者更好的是,在第一次迭代时总结一下:

    for line in fhand:
        if line.startswith("X-DSPAM-Confidence: ") :
            spam = line[19:].strip()
            sum += float (spam) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 2022-12-10
      • 2014-01-24
      • 1970-01-01
      相关资源
      最近更新 更多