programing

목록의 평균 찾기

randomtip 2022. 9. 8. 21:44
반응형

목록의 평균 찾기

Python에서 목록의 평균 평균을 찾는 방법은 무엇입니까?

[1, 2, 3, 4]  ⟶  2.5

Python 3.8+의 경우는, 플로트로 수치 안정성을 실현합니다.(고속)

Python 3.4+의 경우 플로트를 사용하여 수치 안정성을 확보합니다.(저속)

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

import statistics
statistics.mean(xs)  # = 20.11111111111111

이전 버전의 Python 3의 경우,

sum(xs) / len(xs)

Python 2의 경우 변환len플로트 분할을 위해 플로트로 이동:

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

사용방법:

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

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

Python 3.4+의 경우 새 모듈에서 다음을 사용하여 평균을 계산합니다.

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

왜 사용합니까?reduce()파이썬이 완벽한 크롬을 가지고 있을 때sum()기능하고 있습니까?

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

(the.float()Python 2에서는 Python이 부동소수점 나눗셈을 하도록 강제하기 위해 필요합니다.)

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, 분산, 모드, 고조파 평균, 중위수 등과 같이 너무 유용한 다른 방법이 있습니다.

플로트에 주조하는 대신 합계에 0.0을 추가할 수 있습니다.

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

편집:

리스트의 평균을 얻기 위한 두 가지 방법을 추가했습니다(Python 3.8+에만 해당).다음은 제가 비교한 내용입니다.

import timeit
import statistics
import numpy as np
from functools import reduce
import pandas as pd
import math

LIST_RANGE = 10
NUMBERS_OF_TIMES_TO_TEST = 10000

l = list(range(LIST_RANGE))

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 = 10
NUMBERS_OF_TIMES_TO_TEST = 10000

l = list(range(LIST_RANGE))

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)

sum(l) / float(len(l))이것이 정답입니다만, 완전성을 위해서, 1회의 삭감만으로 평균을 계산할 수 있습니다.

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

이로 인해 약간의 반올림 오류가 발생할 수 있습니다.

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

위의 옵션을 사용해 봤지만 효과가 없었습니다.이것을 시험해 보세요.

from statistics import mean

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

print(n)
print(mean(n))

python 3.5에서 작업했습니다.

또는 사용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

나도 Udacity의 문제에서 풀어야 할 비슷한 질문이 있었다.내장 함수 대신 코드화:

def list_mean(n):

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

평소보다 훨씬 더 길지만 초보자에게는 꽤 어렵다.

초심자로서 이걸 코드화했어

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)

평균(일명 평균) 이상의 정보를 얻고 싶다면 다음과 같은 통계 정보를 확인할 수 있습니다.

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)

「 」를 하려면 , 「 」를 합니다.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

둘 다 정수 또는 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

@앤드류 클라크의 말은 옳았다.

라고 가정하다

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*10을 할 는 3입니다.mean할 수 .

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

말고 꼭 해 주세요import numpy as np

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

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

다음 PYTON 코드를 사용하여 목록에서 평균을 찾습니다.

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

쉽게 해봐.

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

또는 이전에 게시된 것과 같습니다.

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

1.0은 부동소수점 분할을 확실하게 하기 위한 것입니다.

몇 저는 줄일 수 있지 않다고 .이러한 답변은 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

다른 접근방식을 추가하고 싶다.

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

평균, 사용량에 대한 함수를 만들 수 있습니다.

average(21,343,2983) # You can pass as many arguments as you want.

코드는 다음과 같습니다.

def average(*args):
    total = 0
    for num in args:
        total+=num
    return total/len(args)

*args는 임의의 수의 답변을 허용합니다.

심플한 솔루션은 아베메디 립입니다.

pip install avemedi_lib

스크립트에 포함시키다

from avemedi_lib.functions import average, get_median, get_median_custom


test_even_array = [12, 32, 23, 43, 14, 44, 123, 15]
test_odd_array = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Getting average value of list items
print(average(test_even_array))  # 38.25

# Getting median value for ordered or unordered numbers list
print(get_median(test_even_array))  # 27.5
print(get_median(test_odd_array))  # 27.5

# You can use your own sorted and your count functions
a = sorted(test_even_array)
n = len(a)

print(get_median_custom(a, n))  # 27.5

즐거운 시간 되세요.

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)

언급URL : https://stackoverflow.com/questions/9039961/finding-the-average-of-a-list

반응형