[英]How to average multiple inputs in Python in a condensed form?
I have many, many numbers to write and it is simply not efficient to write out... 我写了很多很多的数字,写出来的效率根本不高
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
c = float(input("Enter the third number: "))
...when you have a thousand numbers. ......当你拥有一千个号码时 So how can I use the range feature maybe to get many numbers from a single input line and then also calculate the mean or average of all of the inputs?
那么如何使用范围特征从单个输入线获取许多数字,然后计算所有输入的平均值或平均值?
One way is to use a for loop to repeatedly query for the numbers. 一种方法是使用for循环重复查询数字。 If only the average is needed, it's sufficient to just increment a single variable and divide by the total number of queries at the end:
如果只需要平均值,只需增加一个变量并除以最后的查询总数就足够了:
n = 10
temp = 0
for i in range(n):
temp += float(input("Enter a number"))
print("The average is {}".format(temp / n))
By using the built-in sum() function and generator comprehension it's possible to shorten that code alot: 通过使用内置的sum()函数和生成器理解 ,可以缩短代码很多:
n = 10
average = sum(float(input("Enter a number")) for i in range(n)) / n
print("The average is {}".format(average))
A concise way is with a list comprehension. 简洁的方法是列表理解。
nums = [float(input('enter number {}: '.format(i+1))) for i in range(100)]
Replace 100 with any range you like. 将100替换为您喜欢的任何范围。 This will create a list of input numbers.
这将创建一个输入数字列表。 You can access the n'th input number with
nums[n-1]
. 您可以使用
nums[n-1]
访问第n个输入数字。
Alternatively, you could parse a single input string into a list of floats: 或者,您可以将单个输入字符串解析为浮点列表:
>>> nums = [float(x) for x in input('enter numbers: ').split()]
enter numbers: 1.0 3.14 7.124 -5
>>> nums
[1.0, 3.14, 7.124, -5.0]
I'd prefer that over a lot of prompts. 在很多提示中我更喜欢这个。
Finally, if getting the numbers from the command line is an option, you can do it like this 最后,如果从命令行获取数字是一个选项,您可以这样做
import sys
nums = [float(x) for x in sys.argv[1:]]
print(nums)
Demo: 演示:
$ python3 getinput.py 1.0 -5.37 8.2
[1.0, -5.37, 8.2]
To get the mean, issue sum(nums)/len(nums)
, assuming that your list is not empty. 要获得均值,请发出
sum(nums)/len(nums)
,假设您的列表不为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.