python - python 打开文本文件读取并求平均值

标签 python python-3.x

嗨,所以我目前正在尝试编写一个代码,该代码需要几天的时间,然后打开多个文本文件(temps1.txt 等),读取它们,将它们按平均值排序到字典中,然后将其打印出来。然而,有些平均值的小数位数非常多

f = {}
ans = int(input('How many days of data do you have? '))
#figure out how to open certain files
for file_num in range(1, (ans+1)):
    file_name = "temps" + str(file_num) + ".txt"
    temps = open(file_name)
    for line in temps:
        room, num = line.strip('\n').split(',')
        num = int(num)
        #may need to be 4* however many times it appears
        num = num/(4*ans)
        f[room] = f.get(room, 0) + num

print('Average Temperatures:')
for x in f:
     print (x + ':',f[x])

我有一个名为卧室的房间示例(文本文件中所有卧室的平均值),平均值为 26.0,但它打印出来为 26.000000000000004 我如何阻止它这样做?

最佳答案

你可以告诉 Python 如何格式化数字,如下所示:

print('Average Temperatures:')
for x in f:
     print ('%.1f:' % x, f[x])

%.1f 表示打印为 float ,小数点后有 1 个数字。

关于python - python 打开文本文件读取并求平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52089195/

相关文章:

python - 在 python 中隐藏或删除 tkinter 的菜单栏

python - 使用双循环创建 DataFrame

python - 如何使用Python删除csv文件中的双引号(")?

python - 解析预期输出

python-3.x - Pygame TypeError : 'int' object is not callable

python - 如何删除字符串中*在特定分隔符*内的特定字符*,例如括号内

python-3.x - 获取半径内相邻元素的索引

Python:绘制筛选点返回图片上的点

python - python matplotlib中基于颜色条的图例

python - 将 NumPy np.uint8 数组列表转换为 np.unicode_ 数组