嗨,所以我目前正在尝试编写一个代码,该代码需要几天的时间,然后打开多个文本文件(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/