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

标签 python math external-data-source

有人可以帮助您了解如何将数学添加到已创建的将输出写入文本文件的函数中吗?第一个任务是将数字从最低到最高的值写入到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()

最佳答案

您需要将文本数字解析为int,以便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

关于python - 如何将数学添加到函数中以写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60058861/

相关文章:

python - 如何将元组的 Python 生成器拆分为 2 个独立的生成器?

python - 为什么我的 extjs 组合框没有动态填充?

python - 基于列而不是行索引/索引的 Bokeh 链接/刷光

java - 为具有菱形图 block 的游戏改变鼠标位置背后的数学原理是什么?

c - 如何从用户那里获取两个二进制数和运算并给出答案

python - 如何对数字进行排序并写入新的文本文件

python - 检查变量是否为 None 或 numpy.array

math - 如何组合复杂的多边形?

python - 检查文本文件中的日期是否过期

SQL Azure - 创建外部数据源 : Location as a Parameter?