Encuentra el promedio de una lista en python

Requisitos previos: función sum() , función len() , función round(), reduce(), lambda y mean() . Dada una lista de números, la tarea es encontrar el promedio de esa lista. El promedio es la suma de los elementos dividida por el número de elementos.

Input : [4, 5, 1, 2, 9, 7, 10, 8]
Output : Average of the list = 5.75
Explanation:
Sum of the elements is 4+5+1+2+9+7+10+8 = 46
and total number of elements is 8.
So average is 46 / 8 = 5.75

Input : [15, 9, 55, 41, 35, 20, 62, 49]
Output : Average of the list = 35.75
Explanation:
Sum of the elements is 15+9+55+41+35+20+62+49 = 286
and total number of elements is 8.
So average is 46 / 8 = 35.75
usando sum()

En Python podemos encontrar el promedio de una lista simplemente usando la función sum() y len() .

Python3

# Python program to get average of a list
def Average(lst):
    return sum(lst) / len(lst)
  
# Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
  
# Printing average of the list
print("Average of the list =", round(average, 2))

Python3

# Python program to get average of a list
# Using reduce() and lambda 
  
# importing reduce()
from functools import reduce
  
def Average(lst):
    return reduce(lambda a, b: a + b, lst) / len(lst)
  
# Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
  
# Printing average of the list
print("Average of the list =", round(average, 2))

Python3

# Python program to get average of a list
# Using mean()
  
# importing mean()
from statistics import mean
  
def Average(lst):
    return mean(lst)
  
# Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
  
# Printing average of the list
print("Average of the list =", round(average, 2))

Python3

# Python code to get average of list
def Average(lst):
    sum_of_list = 0
    for i in range(len(lst)):
        sum_of_list += lst[i]
    average = sum_of_list/len(lst)
    return average
  
  
# Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
print("Average of the list =", round(average, 2))

Publicación traducida automáticamente

Artículo escrito por Chinmoy Lenka y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *