有人可以帮助正确的方法或对此有意见。我已经编写了下面的代码,该代码应该从文本文件中获取输入,按顺序排列一行,并声明这是最小数字,然后在下一行相同的最大数字,最后是所有数字的平均值。
我的代码:
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()