如何使用python查找文本文件中的整数范围

时间:2018-11-19 22:46:19

标签: python range text-files

在我的文本文件中找到平均值之后,我想知道如何在同一文本文件中找到相同值的范围。

我现在所拥有的:

file = open('stats.txt', 'a+')
file.write('\n' + 'Score: ' +str(score))
file.close()

with open('stats.txt') as fh:
    sum = 0
    count = 0
    for line in fh:
        count += 1 
        sum += float(line.split()[1])
    average = sum / count

#add range here

file = open('maths.txt', 'w+')
file.write('Average: ' + str(average))
file.close()

文本文件stats.txt如下所示:

Score: 3
Score: 0
Score: 13
Score: 13
Score: 9
Score: 0
Score: 0
Score: 0
Score: 0
Score: 0
Score: 0
Score: 31
Score: 0
Score: 0
Score: 0
Score: 0
Score: -8
Score: 0
Score: 0

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

类似这样的东西:

file = open('stats.txt', 'a+')
file.write('\n' + 'Score: ' + str(1))
file.close()

numbers = []
with open('stats.txt') as fh:
    count = 0
    for line in fh:
        count += 1
        numbers.append(float(line.split()[1]))

file = open('maths.txt', 'w+')
file.write('Average: ' + str(sum(numbers)/len(numbers)) + "\n")
file.write('Max: ' + str(max(numbers)) + "\n")
file.write('Min: ' + str(min(numbers)) + "\n")
file.close()