简体   繁体   English

从 .txt 文件中读取数据并在 Python 中计算平均值

[英]Reading data from .txt file and calculating mean in Python

I have a question about my Python code.我有一个关于我的 Python 代码的问题。 I would like to read data from a .txt file and calculate the average of these values.我想从.txt文件中读取数据并计算这些值的平均值。 The format of the .txt file is (1 vertical column): .txt文件的格式为(1 个垂直列):

1.36
5.5
6.11
12.05
25.8
38.28

The code that I have written is:我写的代码是:

 from statistics import mean

 with open('inputdata.txt','r') as fin:
     data=fin.read().split('\n')
     for index in range(len(data)):
         average=mean(float(index))

  print(average)

I used the above code, but in command window shows the following message:我使用了上面的代码,但在命令窗口中显示以下消息:

if iter(data) is data:
TypeError: 'float' object is not iterable

Could anyone help me?有人可以帮助我吗?

You can create a list of values by splitting by '\\n' and convert those values to float, after that you can calculate the mean of that list using the mean from statistics:您可以通过按 '\\n' 拆分来创建值列表并将这些值转换为浮点数,然后您可以使用统计数据的平均值计算该列表的平均值:

from statistics import mean

with open('inputdata.txt','r') as fin:
    data=[float(x) for x in fin.read().split('\n')]

average = mean(data)
print(average)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM