python - 如何以简明形式对 Python 中的多个输入进行平均?

标签 python python-3.x

我有很多很多数字要写,写出来效率很低...

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/

相关文章:

Python Scrapy 提取 aria-label 的值

python - 扩展类(Monkey Patching)如何在 Python 中工作?

python - 在 Django 中使用多个时区

python-3.x - 当处理程序在 AWS lambda 中超时时如何处理剩余的负载?

python - 在 Python 3 中正确使用全局变量

python - Pandas :根据列的值对行进行排序

python - 在Python中查找多个重叠矩形的交集区域

python - 从根到选定节点的树路径 - Pythonic 方式

python-3.x - 用 Selenium 刮活聊天直到流结束

python - Python函数的Dask Apply