编写程序来计算和打印文本文件中数字的平均值,其中包括使用两个高阶函数的文本和数字



如何编写程序来计算和打印文本文件中数字的平均值,其中包括使用两个高阶函数的文本和数字?

文本文件的输入类似于:

Age of ram is 40.his fathers age is 90.he has 4 cars, & 8 two wheelers.

我必须找到这里存在的整数值的平均值,忽略字母表。

我在其他文件中尝试过,只是包含整数,而不是字母

import functools
file = open("integers.txt", 'r')
file = file.read()
file = file.split()
file = list(map(int, file))
print(functools.reduce(lambda x, y: x+y / len(file), file, 0))
text = 'Age of ram is 40.his fathers age is 90.he has 4 cars, & 8 two wheelers.'
# Replace other characters with space and join them
# Split to get numbers
number_txt = ''.join([c if c.isdigit() else ' ' for c in text]).split()
# Convert number text to int
numbers = list(map(int, number_txt))
# Find average
avg = sum(numbers)/len(numbers)

最新更新