平均-Python [英] Average -Python
问题描述
我正在尝试查找范围内数字的平均值(即查找范围1-1000中所有数字的平均值).我编写了以下代码来执行此操作,但是由于if-statement
,在运行时,该代码会产生多个数字.然后,我尝试使用while-loop
,但是当我输入break
语句时,它产生的list
与产生的if-statement
相同.有什么方法可以使用if-statement
并获得1个平均数吗?谢谢!
I am trying to find the average of numbers in ranges (i.e. find the average of all numbers in range 1-1000). I wrote the following code to do this, but the due to the if-statement
, when run, the code produces multiple numbers. I then tried a while-loop
instead, but when I entered a break
statement, it produced the same list
the if-statement
produced. Is there any way to use an if-statement
and get 1 single number that is the average? Thank you!
mylist =[]
def ave_data(x, y):
for line in filename:
for number in line.split():
if int(number) > x and int(number) < y:
mylist.append(int(number))
print(sum(mylist)/len(mylist))
推荐答案
由于if语句,它不是 .您只需将print(..)
放在for
循环的if
中.通过将其移动到外部for
之外,它将打印整个文件的平均值 :
It is not due to the if statement. You simply put the print(..)
in the if
in the for
loop. By moving it outside the outer for
, it will print the average for the entire file:
def ave_data(x, y):
mylist = [] # move inside
for line in filename:
for number in line.split():
if int(number) > x and int(number) < y:
mylist.append(int(number))
print(sum(mylist)/len(mylist)) # for the entire file.
您还可以在功能内 中更好地移动mylist
变量.否则,它是一个全局变量,其他函数可以对其进行更改.此外,第二轮运行将取两个文件的平均值.
You also move the mylist
variable better inside the function. Otherwise it is a global variable, and other functions can alter it. Furthermore a second run would take the average of the two files.
话虽这么说,您会使事情变得太复杂了.您可以简单地使用:
That being said, you make things too complicated. You can simply use:
def ave_data(x, y):
mylist = [int(number) for line in filename for number in line.split()
if x < int(number) < y]
print(sum(mylist)/len(mylist)) # for the entire file.
这篇关于平均-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!