问题:查找列表的平均值

我必须在Python中找到列表的平均值。到目前为止,这是我的代码

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)

我已经知道了,所以它可以将列表中的值加在一起,但是我不知道如何将其划分为它们?

I have to find the average of a list in Python. This is my code so far

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)

I’ve got it so it adds together the values in the list, but I don’t know how to make it divide into them?


回答 0

在Python 3.4+上,您可以使用 statistics.mean()

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]

import statistics
statistics.mean(l)  # 20.11111111111111

在旧版本的Python上,您可以执行

sum(l) / len(l)

在Python 2上,您需要转换len为浮点数才能进行浮点数除法

sum(l) / float(len(l))

无需使用reduce。它慢得多,并在Python 3 中删除

On Python 3.4+ you can use statistics.mean()

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]

import statistics
statistics.mean(l)  # 20.11111111111111

On older versions of Python you can do

sum(l) / len(l)

On Python 2 you need to convert len to a float to get float division

sum(l) / float(len(l))

There is no need to use reduce. It is much slower and was removed in Python 3.


回答 1

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(l) / len(l)
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(l) / len(l)

回答 2

您可以使用numpy.mean

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]

import numpy as np
print(np.mean(l))

You can use numpy.mean:

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]

import numpy as np
print(np.mean(l))

回答 3

一个统计模块已经加入到了Python 3.4。它具有计算平均值的功能,称为均值。您提供的列表的示例为:

from statistics import mean
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
mean(l)

A statistics module has been added to python 3.4. It has a function to calculate the average called mean. An example with the list you provided would be:

from statistics import mean
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
mean(l)

回答 4

reduce()当Python具有完美的sum()功能时,为什么要使用此功能?

print sum(l) / float(len(l))

float()必须强制Python执行浮点除法。)

Why would you use reduce() for this when Python has a perfectly cromulent sum() function?

print sum(l) / float(len(l))

(The float() is necessary to force Python to do a floating-point division.)


回答 5

如果您使用的是python> = 3.4,则有一个统计资料库

https://docs.python.org/3/library/statistics.html

您可以使用这种卑鄙的方法。假设您有一个要查找均值的数字列表:-

list = [11, 13, 12, 15, 17]
import statistics as s
s.mean(list)

它还有其他方法,如stdev,方差,众数,谐波均值,中位数等,这些方法也非常有用。

There is a statistics library if you are using python >= 3.4

https://docs.python.org/3/library/statistics.html

You may use it’s mean method like this. Let’s say you have a list of numbers of which you want to find mean:-

list = [11, 13, 12, 15, 17]
import statistics as s
s.mean(list)

It has other methods too like stdev, variance, mode, harmonic mean, median etc which are too useful.


回答 6

除了将其强制转换为浮点数外,还可以在总和上加上0.0:

def avg(l):
    return sum(l, 0.0) / len(l)

Instead of casting to float, you can add 0.0 to the sum:

def avg(l):
    return sum(l, 0.0) / len(l)

回答 7

sum(l) / float(len(l)) 是正确的答案,但仅出于完整性考虑,您可以通过一次减少来计算平均值:

>>> reduce(lambda x, y: x + y / float(len(l)), l, 0)
20.111111111111114

请注意,这可能会导致轻微的舍入错误:

>>> sum(l) / float(len(l))
20.111111111111111

sum(l) / float(len(l)) is the right answer, but just for completeness you can compute an average with a single reduce:

>>> reduce(lambda x, y: x + y / float(len(l)), l, 0)
20.111111111111114

Note that this can result in a slight rounding error:

>>> sum(l) / float(len(l))
20.111111111111111

回答 8

我尝试使用上面的选项,但是没有用。尝试这个:

from statistics import mean

n = [11, 13, 15, 17, 19]

print(n)
print(mean(n))

在python 3.5上工作

I tried using the options above but didn’t work. Try this:

from statistics import mean

n = [11, 13, 15, 17, 19]

print(n)
print(mean(n))

worked on python 3.5


回答 9

或使用pandasSeries.mean方法:

pd.Series(sequence).mean()

演示:

>>> import pandas as pd
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> pd.Series(l).mean()
20.11111111111111
>>> 

从文档:

Series.mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

这是文档:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mean.html

以及整个文档:

https://pandas.pydata.org/pandas-docs/stable/10min.html

Or use pandas‘s Series.mean method:

pd.Series(sequence).mean()

Demo:

>>> import pandas as pd
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> pd.Series(l).mean()
20.11111111111111
>>> 

From the docs:

Series.mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

And here is the docs for this:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mean.html

And the whole documentation:

https://pandas.pydata.org/pandas-docs/stable/10min.html


回答 10

在Udacity的问题中,我也有类似的问题要解决。我编码的不是内置函数:

def list_mean(n):

    summing = float(sum(n))
    count = float(len(n))
    if n == []:
        return False
    return float(summing/count)

比平常更长的时间,但是对于初学者来说,这是一个很大的挑战。

I had a similar question to solve in a Udacity´s problems. Instead of a built-in function i coded:

def list_mean(n):

    summing = float(sum(n))
    count = float(len(n))
    if n == []:
        return False
    return float(summing/count)

Much more longer than usual but for a beginner its quite challenging.


回答 11

作为一个初学者,我只是编写了这样的代码:

L = [15, 18, 2, 36, 12, 78, 5, 6, 9]

total = 0

def average(numbers):
    total = sum(numbers)
    total = float(total)
    return total / len(numbers)

print average(L)

as a beginner, I just coded this:

L = [15, 18, 2, 36, 12, 78, 5, 6, 9]

total = 0

def average(numbers):
    total = sum(numbers)
    total = float(total)
    return total / len(numbers)

print average(L)

回答 12

如果您想获得的不仅仅是平均值(也就是平均值),您可以查看scipy统计信息

from scipy import stats
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(stats.describe(l))

# DescribeResult(nobs=9, minmax=(2, 78), mean=20.11111111111111, 
# variance=572.3611111111111, skewness=1.7791785448425341, 
# kurtosis=1.9422716419666397)

If you wanted to get more than just the mean (aka average) you might check out scipy stats

from scipy import stats
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(stats.describe(l))

# DescribeResult(nobs=9, minmax=(2, 78), mean=20.11111111111111, 
# variance=572.3611111111111, skewness=1.7791785448425341, 
# kurtosis=1.9422716419666397)

回答 13

为了reduce用于获得运行平均值,您需要跟踪总数,但也要跟踪到目前为止看到的元素总数。由于这不是列表中的琐碎元素,因此您还必须传递reduce一个额外的参数以使其折叠。

>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> running_average = reduce(lambda aggr, elem: (aggr[0] + elem, aggr[1]+1), l, (0.0,0))
>>> running_average[0]
(181.0, 9)
>>> running_average[0]/running_average[1]
20.111111111111111

In order to use reduce for taking a running average, you’ll need to track the total but also the total number of elements seen so far. since that’s not a trivial element in the list, you’ll also have to pass reduce an extra argument to fold into.

>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> running_average = reduce(lambda aggr, elem: (aggr[0] + elem, aggr[1]+1), l, (0.0,0))
>>> running_average[0]
(181.0, 9)
>>> running_average[0]/running_average[1]
20.111111111111111

回答 14

两者都可以为您提供接近整数或至少10个十进制值的相似值。但是,如果您真正考虑的是长浮点值,则两者可能会有所不同。方法可能因您要实现的目标而异。

>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> print reduce(lambda x, y: x + y, l) / len(l)
20
>>> sum(l)/len(l)
20

浮动值

>>> print reduce(lambda x, y: x + y, l) / float(len(l))
20.1111111111
>>> print sum(l)/float(len(l))
20.1111111111

@安德鲁·克拉克(Andrew Clark)的发言是正确的。

Both can give you close to similar values on an integer or at least 10 decimal values. But if you are really considering long floating values both can be different. Approach can vary on what you want to achieve.

>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> print reduce(lambda x, y: x + y, l) / len(l)
20
>>> sum(l)/len(l)
20

Floating values

>>> print reduce(lambda x, y: x + y, l) / float(len(l))
20.1111111111
>>> print sum(l)/float(len(l))
20.1111111111

@Andrew Clark was correct on his statement.


回答 15

假设

x = [[-5.01,-5.43,1.08,0.86,-2.67,4.94,-2.51,-2.25,5.56,1.03], [-8.12,-3.48,-5.52,-3.78,0.63,3.29,2.09,-2.13,2.86,-3.33], [-3.68,-3.54,1.66,-4.11,7.39,2.08,-2.59,-6.94,-2.26,4.33]]

您会注意到它的x尺寸为3 * 10,如果您需要mean进入每一行,则可以键入

theMean = np.mean(x1,axis=1)

别忘了 import numpy as np

suppose that

x = [[-5.01,-5.43,1.08,0.86,-2.67,4.94,-2.51,-2.25,5.56,1.03], [-8.12,-3.48,-5.52,-3.78,0.63,3.29,2.09,-2.13,2.86,-3.33], [-3.68,-3.54,1.66,-4.11,7.39,2.08,-2.59,-6.94,-2.26,4.33]]

you can notice that x has dimension 3*10 if you need to get the mean to each row you can type this

theMean = np.mean(x1,axis=1)

don’t forget to import numpy as np


回答 16

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]

l = map(float,l)
print '%.2f' %(sum(l)/len(l))
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]

l = map(float,l)
print '%.2f' %(sum(l)/len(l))

回答 17

使用以下PYTHON代码在列表中查找平均值:

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(sum(l)//len(l))

试试这个很容易。

Find the average in list By using the following PYTHON code:

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(sum(l)//len(l))

try this it easy.


回答 18

print reduce(lambda x, y: x + y, l)/(len(l)*1.0)

或喜欢以前发布的

sum(l)/(len(l)*1.0)

1.0是确保获得浮点除法

print reduce(lambda x, y: x + y, l)/(len(l)*1.0)

or like posted previously

sum(l)/(len(l)*1.0)

The 1.0 is to make sure you get a floating point division


回答 19

结合以上几个答案,我提出了以下与reduce一起使用的方法,并且不假定您在reduce L函数中可用:

from operator import truediv

L = [15, 18, 2, 36, 12, 78, 5, 6, 9]

def sum_and_count(x, y):
    try:
        return (x[0] + y, x[1] + 1)
    except TypeError:
        return (x + y, 2)

truediv(*reduce(sum_and_count, L))

# prints 
20.11111111111111

Combining a couple of the above answers, I’ve come up with the following which works with reduce and doesn’t assume you have L available inside the reducing function:

from operator import truediv

L = [15, 18, 2, 36, 12, 78, 5, 6, 9]

def sum_and_count(x, y):
    try:
        return (x[0] + y, x[1] + 1)
    except TypeError:
        return (x + y, 2)

truediv(*reduce(sum_and_count, L))

# prints 
20.11111111111111

回答 20

我想添加另一种方法

import itertools,operator
list(itertools.accumulate(l,operator.add)).pop(-1) / len(l)

I want to add just another approach

import itertools,operator
list(itertools.accumulate(l,operator.add)).pop(-1) / len(l)

回答 21

numbers = [0,1,2,3]

numbers[0] = input("Please enter a number")

numbers[1] = input("Please enter a second number")

numbers[2] = input("Please enter a third number")

numbers[3] = input("Please enter a fourth number")

print (numbers)

print ("Finding the Avarage")

avarage = int(numbers[0]) + int(numbers[1]) + int(numbers[2]) + int(numbers [3]) / 4

print (avarage)
numbers = [0,1,2,3]

numbers[0] = input("Please enter a number")

numbers[1] = input("Please enter a second number")

numbers[2] = input("Please enter a third number")

numbers[3] = input("Please enter a fourth number")

print (numbers)

print ("Finding the Avarage")

avarage = int(numbers[0]) + int(numbers[1]) + int(numbers[2]) + int(numbers [3]) / 4

print (avarage)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。