如何正确使用外部文本文件



有人可以帮忙提供正确的方法或对此发表意见吗?我编写了下面的代码,应该从文本文件中获取输入,按顺序排列一行并说明哪个是最小数字,然后在下一行上相同,用于最大数字,最后是所有数字的平均值。

我的代码:

from statistics import mean
def number1():
with open('input.txt') as file:
data = {line.split(':')[0]: sorted([int(value) for value in line.split(':')[1].split(',')]) for line in file.readlines()}
functions = {'min': min, 'max': max, 'avg': mean}
with open('output.txt', 'w') as file:
file.writelines(f"The {function} of {values} is {functions[function](values)}n" for function, values in data.items())
number1()

有人告诉我这是不正确的。下面是建议我应该使用的代码,但在清除我认为正确的缩进之后。我只得到平均线的输出。

建议代码:

outfile = open("output.txt", "w")
with open("input.txt") as f:
for line in f:
# clean line and split into operator and data
operator, data = line.lower().strip().split(":")
line = line.split(":")
operator = line[0].lower().strip()
data = line[1].strip().split(",")
# parse data into list of integers
# data = [int(x) for x in data.split(",")]
# convert numbers in list to integer
newData = []
for x in data:
newData.append(int(x))
# min(), max(), sum(), len()
# determine operation to perform on number list variable
if operator == "min":
result = min(newData)
elif operator == "max":
result = max(newData)
elif operator == "avg":
result = sum(newData) / len(newData)
# create output string
report_line = "The {} of {} is {}.n".format(operator, newData, result)
outfile.write(report_line)
outfile.close()        

您可以使用以下逻辑。

假设您的文本文件是数据.txt内容如下

3 7 5 
0 4 2 
8 1 6 
2 6 3 
1 0 8 
5 4 7 
4 1 6 
0 8 7 
2 3 5 
7 2 6 
4 1 3 
8 0 5 

使用以下代码将所有数字插入列表并查找最小值和最大值。

list = []
file = open('data.txt', 'r')
for line in file.readlines():
for n in line:
if (n!=" " and  n!="n"):
list.append(n)
print(list)
print(min(list),max(list))

相关内容

  • 没有找到相关文章

最新更新