Finding average in .txt file python

回眸只為那壹抹淺笑 提交于 2021-02-05 09:24:26

问题


i need to print out average height from a .txt file. How do I write it in an easy way? The .txt file has these numbers:

12
14
59
48
45
12
47
65
152

this is what i've got so far:

import math

text = open(r'stuff.txt').read()
data = []
with open(r'stuff.txt') as f:
    for line in f:
        fields = line.split()
        rowdata = map(float, fields)
        data.extend(rowdata)

biggest = min(data)
smallest = max(data)
print(biggest - smallest)

回答1:


To compute the average of some numbers, you should sum them up and then divide by the number of numbers:

data = []
with open(r'stuff.txt') as f:
    for line in f:
        fields = line.split()
        rowdata = map(float, fields)
        data.extend(rowdata)

print(sum(data)/len(data))



回答2:


# import math -- you don't need this

# text = open(r'stuff.txt').read() not needed.
# data = [] not needed

with open(r'stuff.txt') as f:
    data = [float(line.rstrip()) for line in f]

biggest = min(data)
smallest = max(data)
print(biggest - smallest)
print(sum(data)/len(data))



回答3:


data = [float(ln.rstrip()) for ln in f.readlines()]  # Within 'with' statement.
mean_average = float(sum(data))/len(data) if len(data) > 0 else float('nan')

That is the way to calculate the mean average, if that is what you meant. Sadly, math does not have a function for this. FYI, the mean_average line is modified in order to avoid the ZeroDivisionError bug that would occur if the list had a length of 0- just in case.




回答4:


Array average can be computed like this:

print(sum(data) / len(data))



回答5:


A simple program for finding the average would be the following (if I understand well, your file has one value in each line, if so, it has to be similar to this, else it has to change accordingly):

import sys

f = open('stuff.txt', 'rU')    
lines = f.readlines()    
f.close()

size =  len(lines)
sum=0
for line in lines:
    sum = sum + float(line.rstrip())

avg = sum / float(size)    
print avg,

Not the best that can be in python but it's quite straight forward I think...




回答6:


A full, almost-loopless solution combining elements of other answers here:

with open('stuff.txt','r') as f:
    data = [float(line.rstrip()) for line in f.readlines()]
    f.close()
mean = float(sum(data))/len(data) if len(data) > 0 else float('nan')

and you don't need to prepend, append, enclose or import anything else.



来源:https://stackoverflow.com/questions/22410448/finding-average-in-txt-file-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!