开放阅读和平均文本文件python

问题描述 投票:1回答:3

嗨,所以我正在尝试编写一个代码,要求几天,然后打开多个文本文件(temps1.txt等),读取它们,将它们分类为平均值的dictionarys然后打印出来。然而,一些平均值具有极小的小数点

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 python-3.x
3个回答
2
投票

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

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

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


0
投票

查看'round()'函数。退房:How to round down to 2 decimals with Python?

>>> x = 26.000000000000004
>>> print str(round(x, 2))  
>>> '26.00'

0
投票

您可以使用:

for x in f:
    print("{:.2f}".format(float(x)))

.2f表示点后2位数。有关更多选项,请参阅https://docs.python.org/3.7/library/string.html#formatstrings

© www.soinside.com 2019 - 2024. All rights reserved.