我怎样才能写一段额外的代码来把我所有的输出加在一起?

How can I write an additional piece of code to add all my outputs together?

所以我写了这段代码 returns mean file.[=13 前三行的 mean =]

import statistics
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        print((statistics.mean(h)))

我正确地得到了输出,即

100.177647525
97.27899259
100.2046613525

现在我想写一个额外的代码块,将这段代码的输出加在一起,换句话说,我想把 100.177647525、97.27899259 和 100.2046613525 加在一起。我试图通过写这篇文章来做到这一点..

import statistics
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        print((statistics.mean(h)))
s = 0
for x in statistics.mean(h):
    s += x
print(s)

但我收到一条错误消息,指出 “类型错误:'float' 对象不可迭代”。那么我应该做哪些更改才能使这项工作正常进行?

statistics.mean() returns 浮点数,不是迭代器。你实际上打印了这个函数三次,每次一次用于你的第一个 for 循环,for x in g。 不要使用第二个 for 循环,只需初始化一个变量并将每个均值添加到它。

import statistics
running_sum = 0
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        mean = statistics.mean(h)
        running_sum += mean
        print(mean)
print(running_sum)

您需要将值存储在变量中,或者可以附加一个包含所有值的列表,如下所示: ####解决方案 1:将值存储在列表中####


import statistics
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    sum_list = []
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        print((statistics.mean(h)))
        sum_list.append(statistics.mean(h))
    total = sum(sum_list)
print(total) 

####解决方案 2:继续将值添加到变量####


import statistics
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    count = 0
    total = 0
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        print((statistics.mean(h)))
        count = statistics.mean(h)
        total = total + count
print(total)

我还没有 运行 这些代码,但我认为它们应该可以工作。