我有很多很多数字要写,写出来效率很低...
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
c = float(input("Enter the third number: "))
...当您有上千个数字时。那么我如何使用范围功能从单个输入行中获取多个数字,然后计算所有输入的均值或平均值?
最佳答案
一种方法是使用for 循环 重复查询数字。如果只需要平均值,只需递增一个变量并在末尾除以查询总数就足够了:
n = 10
temp = 0
for i in range(n):
temp += float(input("Enter a number"))
print("The average is {}".format(temp / n))
通过使用内置的 sum()函数和生成器理解可以大大缩短该代码:
n = 10
average = sum(float(input("Enter a number")) for i in range(n)) / n
print("The average is {}".format(average))
关于python - 如何以简明形式对 Python 中的多个输入进行平均?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35468480/