在txt文件中查找列表的最小,最大和平均值

时间:2019-05-11 15:47:15

标签: python

程序必须读取input.txt的内容,找到最小值,最大值和平均值,然后将结果打印到新文件中。

到目前为止,这是我的代码

# to open the txt file in read and write mode
text_file = open('input.txt', 'r+')

# we now create a list for the numbers in the program
number_list = []

# now we create a loop that loops over each line in the txt file
for line in text_file:
    number_list.append(line.split(','))

3 个答案:

答案 0 :(得分:1)

首先,您想使用with之类的上下文管理器来自动打开和关闭文件

然后,您可以使用python内置min maxsum来分别计算最小值,最大值和平均值

#Open the txt file in read and write mode, and get all integers in file
number_list = []
with open('file.txt', 'r') as fp:
    number_list = [int(item) for item in fp.readlines()]

#Calculate minimum, maximum and average and print it
minimum = min(number_list)
maximum = max(number_list)
average = sum(number_list)/len(number_list)

print('min:', minimum, 'max:', maximum, 'avg:', average)

因此,如果input.txt看起来像这样(每行一个数字):

1
2
3
4
5
6
7
8
9
10

输出将为

min: 1 max: 10 avg: 5.5

答案 1 :(得分:0)

首先需要将数组转换为int,然后使用max,min和sum,len函数:

number_list_int = [int(i) for i in number_list[0]]

print(min(number_list_int))
print(max(number_list_int))
print(sum(number_list_int)/len(number_list_int))

答案 2 :(得分:0)

我假设文件包含用换行符分隔的整数值

>>> # Read file into an array and convert string form integers to int
>>> fd = open("nums")
>>> nums = map(int, fd.read().strip().splitlines())
>>> fd.close()
>>> nums
[12, 15, 5, 89, 2, 3, 5, 6, 11]

>>> # Following functions are self explanatory
>>> max(nums)
89
>>> min(nums)
2
>>> sum(nums)
148
>>> len(nums)
9

>>> # write to file
>>> fd = open("result", "w")
>>> fd.write("max: " + str(max(nums)))
>>> fd.write("\nmin: " + str(min(nums)))
>>> fd.write("\navg: " + str(sum(nums) / len(nums)))
>>> fd.close()