合并高阶函数以使用文本文件从数字列表中计算平均值

时间:2018-11-28 05:14:37

标签: python-3.x lambda split mapping higher-order-functions

我需要编写一个程序来计算和打印文本文件中数字的平均值。我需要利用两个高阶函数来简化设计。

我将使用的文本文件(integers.txt)具有以下数字:

5

4

3

2

1

这是我当前拥有的代码:

# I open up the file.
file = open("integers.txt", 'r')
file = file.read()

# I turn it into a list using the split method
file = file.split()

# I turn it into an integer using the map function.
file = map(int, file)

# I then use a for loop to get the total of all numbers in that list
# I then get the average
sum = 0
for numbers in file:
    sum = numbers + sum
print(sum/len(file))

如何在此程序中使用另一个高阶函数?请帮忙。我还是一个初学者。

1 个答案:

答案 0 :(得分:0)

我想出了答案!

import functools

# open your file
file = open("integers.txt", 'r')
file = file.read()

# put numbers into a list
file = file.split()

# convert list into integers
file = list(map(int, file))

# use lambda function to get average.
print(functools.reduce(lambda x, y: x+y / len(file), file, 0))