读取文本文件并在python中查找数字的平均值

时间:2014-10-01 22:15:26

标签: python

我的任务是读取我已经写过的txt文件,在每一行分别显示数字,并使用循环获取数字的平均值。这就是我到目前为止所拥有的。

data = []
def main():
    f = open('tests.txt', 'r')
    for line in tests:
        amout = float(line)
        print(format(amount, '.3f'))
        print avg()
        tests.close()
def avg():
    for line in f:
        fields = line.split()
        rowdata = map(float, fields)
        data.extend(rowdata)
        average = (sum(data)/len(data))
        print("The average is", average)
main()

1 个答案:

答案 0 :(得分:0)

试试这个。它运行在2.5到3.4之间。

#!/usr/local/cpython-3.4/bin/python

'''Compute average of numbers in tests.txt'''

# pylint: disable=superfluous-parens
# superfluous-parens: Parentheses are good for clarity and portability

from __future__ import with_statement


def main():
    '''Main function'''
    numbers = []
    with open('tests.txt', 'r') as file_:
        for line in file_:
            fields = line.split()
            print(line.rstrip('\n'))
            subnumbers = (float(field) for field in fields)
            numbers.extend(subnumbers)
    print('The average is %s' % avg(numbers))


def avg(numbers):
    '''Compute average'''
    average = (sum(numbers)/len(numbers))
    return average

main()

或者作为更大型计划的一部分,请参阅http://stromberg.dnsalias.org/~strombrg/stddev.html

感谢。