编写一个python程序,读取7个分数作为输入并输出平均值[重复]

乘风 python 220

原文标题Write a python program that read 7 scores as input and outputs the average [duplicate]

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

from functools import reduce

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

我已经得到它,所以它将列表中的值加在一起,但我不知道如何将它分成它们?

原文链接:https://stackoverflow.com//questions/71477742/write-a-python-program-that-read-7-scores-as-input-and-outputs-the-average

回复

我来回复
  • yprez的头像
    yprez 评论
    l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
    sum(l) / len(l)
    
    2年前 0条评论
  • Herms的头像
    Herms 评论

    在 Python 3.8+ 上,使用浮点数,您可以使用statistics.fmean,因为使用浮点数更快。

    在 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))
    

    没有必要使用functools.reduce,因为它慢得多。

    2年前 0条评论
  • Akavall的头像
    Akavall 评论

    你可以使用numpy.mean

    l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
    
    import numpy as np
    print(np.mean(l))
    
    2年前 0条评论
  • Marwan Alsabbagh的头像
    Marwan Alsabbagh 评论

    Astatistics 模块已添加到 python 3.4。它有一个计算平均值的函数,称为mean。您提供的列表的示例是:

    from statistics import mean
    l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
    mean(l)
    
    2年前 0条评论
  • kindall的头像
    kindall 评论

    当 Python 有完美的 cromulent sum()函数时,为什么还要使用reduce()呢?

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

    (在 Python 2 中,float() 是强制 Python 进行浮点除法所必需的。)

    2年前 0条评论
  • Chetan Sharma的头像
    Chetan Sharma 评论

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

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

    你可以像这样使用它的平均方法。假设您有一个要查找平均值的数字列表:-

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

    它也有其他方法,例如标准差、方差、众数、调和平均数、中位数等,它们太有用了。

    2年前 0条评论
  • Maxime Chéramy的头像
    Maxime Chéramy 评论

    您可以将 0.0 添加到总和中,而不是强制转换为浮点数:

    def avg(l):
        return sum(l, 0.0) / len(l)
    
    2年前 0条评论
  • Alon Gouldman的头像
    Alon Gouldman 评论

    编辑:

    我添加了另外两种获取列表平均值的方法(仅与 Python 3.8+ 相关)。这是我所做的比较:

    # test mean caculation
    
    import timeit
    import statistics
    import numpy as np
    from functools import reduce
    import pandas as pd
    import math
    
    LIST_RANGE = 10000000000
    NUMBERS_OF_TIMES_TO_TEST = 10000
    
    l = list(range(10))
    
    def mean1():
        return statistics.mean(l)
    
    
    def mean2():
        return sum(l) / len(l)
    
    
    def mean3():
        return np.mean(l)
    
    
    def mean4():
        return np.array(l).mean()
    
    
    def mean5():
        return reduce(lambda x, y: x + y / float(len(l)), l, 0)
    
    def mean6():
        return pd.Series(l).mean()
    
    
    def mean7():
        return statistics.fmean(l)
    
    
    def mean8():
        return math.fsum(l) / len(l)
    
    
    for func in [mean1, mean2, mean3, mean4, mean5, mean6, mean7, mean8 ]:
        print(f"{func.__name__} took: ",  timeit.timeit(stmt=func, number=NUMBERS_OF_TIMES_TO_TEST))
    

    这些是我得到的结果:

    mean1 took:  0.09751558300000002
    mean2 took:  0.005496791999999973
    mean3 took:  0.07754683299999998
    mean4 took:  0.055743208000000044
    mean5 took:  0.018134082999999968
    mean6 took:  0.6663848750000001
    mean7 took:  0.004305374999999945
    mean8 took:  0.003203333000000086
    

    有趣的!看起来math.fsum(l) / len(l)是最快的方式,然后statistics.fmean(l),只有sum(l) / len(l)。好的!

    感谢@Asclepius 向我展示了这两种其他方式!


    旧答案:

    在效率和速度方面,这些是我测试其他答案的结果:

    # test mean caculation
    
    import timeit
    import statistics
    import numpy as np
    from functools import reduce
    import pandas as pd
    
    LIST_RANGE = 10000000000
    NUMBERS_OF_TIMES_TO_TEST = 10000
    
    l = list(range(10))
    
    def mean1():
        return statistics.mean(l)
    
    
    def mean2():
        return sum(l) / len(l)
    
    
    def mean3():
        return np.mean(l)
    
    
    def mean4():
        return np.array(l).mean()
    
    
    def mean5():
        return reduce(lambda x, y: x + y / float(len(l)), l, 0)
    
    def mean6():
        return pd.Series(l).mean()
    
    
    
    for func in [mean1, mean2, mean3, mean4, mean5, mean6]:
        print(f"{func.__name__} took: ",  timeit.timeit(stmt=func, number=NUMBERS_OF_TIMES_TO_TEST))
    

    结果:

    mean1 took:  0.17030245899968577
    mean2 took:  0.002183011999932205
    mean3 took:  0.09744236000005913
    mean4 took:  0.07070840100004716
    mean5 took:  0.022754742999950395
    mean6 took:  1.6689282460001778
    

    这么明显的赢家是:sum(l) / len(l)

    2年前 0条评论
  • Andrew Clark的头像
    Andrew Clark 评论

    sum(l) / float(len(l)) 是正确的答案,但为了完整起见,您可以使用单个 reduce 计算平均值:

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

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

    >>> sum(l) / float(len(l))
    20.111111111111111
    
    2年前 0条评论
  • Ngury Mangueira的头像
    Ngury Mangueira 评论

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

    from statistics import mean
    
    n = [11, 13, 15, 17, 19]
    
    print(n)
    print(mean(n))
    

    在 python 3.5 上工作

    2年前 0条评论
  • U12-Forward的头像
    U12-Forward 评论

    或者用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

    2年前 0条评论
  • Paulo YC的头像
    Paulo YC 评论

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

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

    比平时长得多,但对于初学者来说,这是相当具有挑战性的。

    2年前 0条评论
  • AlmoDev的头像
    AlmoDev 评论

    作为一个初学者,我刚刚编写了这个代码:

    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)
    
    2年前 0条评论
  • jasonleonhard的头像
    jasonleonhard 评论

    如果您想获得的不仅仅是平均值(也就是平均值),您可以查看 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)
    
    2年前 0条评论
  • SingleNegationElimination的头像
    SingleNegationElimination 评论

    为了使用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
    
    2年前 0条评论
  • Superpaul的头像
    Superpaul 评论

    两者都可以在整数或至少 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 的陈述是正确的。

    2年前 0条评论
  • Mohamed A M-Hassan的头像
    Mohamed A M-Hassan 评论

    假设

    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

    2年前 0条评论
  • user1871712的头像
    user1871712 评论
    l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
    
    l = map(float,l)
    print '%.2f' %(sum(l)/len(l))
    
    2年前 0条评论
  • Integraty_beast的头像
    Integraty_beast 评论

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

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

    试试这个很容易。

    2年前 0条评论
  • RussS的头像
    RussS 评论
    print reduce(lambda x, y: x + y, l)/(len(l)*1.0)
    

    或喜欢之前发布的

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

    1.0 是为了确保你得到一个浮点除法

    2年前 0条评论