如何将数学添加到函数中以写入文本文件

How to add math to your functions for writing to a text file

有人可以帮助解决如何将数学添加到已创建的将输出写入文本文件的函数的正确方法。第一个任务是将数字以从低到高的值写入 output.txt 文件,无论是多少个数字。这是我按照下面的代码完成的。我的问题是我现在需要在第一行显示最小数字,在第二行显示最大数字,在第三行显示数字的平均值。如果有人能提供帮助,我将不胜感激

文本文件(input.txt)

min:1,2,3,4,5,6

max:18,25,32,14,15,62

avg:1,2,3,4,5,6

输出应该是:

The min of [1,2,3,4,5,6] is 1

The max of [14,15,18,25,32,62] is 62

The avg of [1,2,3,4,5,6] is 3.4

如前所述,我已经有一个函数可以将数字从低到高排序,这只是为了做数学运算。

到目前为止我的代码:

def number1():
    inputFile = open("input.txt", 'r')
    lineList = inputFile.readlines()
    fileHandle = open('inputcopy.txt', 'a')
    for line in lineList:
        numbers = [int(item) for item in line.split(':')[1].split(',')]
        numbers.sort()
        fileHandle.write("%s\n" % numbers)  
number1()

您可以使用数学函数进行计算。

import statistics

def number1():
    inputFile = open("input.txt", 'r')
    lineList = inputFile.readlines()
    fileHandle = open('inputcopy.txt', 'a')
    for line in lineList:
        numbers = [int(item) for item in line.split(':')[1].split(',')]
        numbers.sort()
        if line.split(':')[0] == 'min':
             fileHandle.write("%s\n" % min(numbers))
        elif line.split(':')[0] == 'max':
             fileHandle.write("%s\n" % max(numbers))
        elif line.split(':')[0] == "avg":
             fileHandle.write("%s\n" & statistics.mean(numbers))  
number1()

看看https://www.geeksforgeeks.org/max-min-python/https://appdividend.com/2019/01/28/python-statistics-tutorial-mean-function-example/

您需要将文本数字解析为 ints,以便 python 可以处理它们并映射数学运算,例如:

from statistics import mean


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()
    )

哪个会给你:

>>> The min of [1, 2, 3, 4, 5, 6] is 1
>>> The max of [14, 15, 18, 25, 32, 62] is 62
>>> The avg of [1, 2, 3, 4, 5, 6] is 3.5