Python find average of list

Как найти среднее значение списка в Python

В этой статье мы рассмотрим различные способы найти среднее значение списка в списке Python. Среднее значение – это значение, которое представляет весь набор элементов данных или элементов.

Формула: Среднее значение = сумма чисел / общее количество.

Методы поиска среднего значения списка

Для вычисления среднего значения списка в Python можно использовать любой из следующих методов:

  • Функция mean();
  • Встроенный метод sum();
  • Методы lambda() и reduce();
  • Метод operator.add().

Функция mean()

Python 3 имеет модуль статистики, который содержит встроенную функцию для вычисления среднего числа. Функция statistics.mean() используется для вычисления среднего входного значения или набора данных.

Функция mean() принимает список, кортеж или набор данных, содержащий числовые значения, в качестве параметра и возвращает среднее значение элементов данных.

from statistics import mean inp_lst = [12, 45, 78, 36, 45, 237.11, -1, 88] list_avg = mean(inp_lst) print("Average value of the list:\n") print(list_avg) print("Average value of the list with precision upto 3 decimal value:\n") print(round(list_avg,3))

В приведенном выше фрагменте кода мы использовали метод statistics.round() для округления выходного среднего до определенного десятичного значения.

statistics.round(value, precision value)
Average value of the list: 67.51375 Average value of the list with precision upto 3 decimal value: 67.514

Использование функции sum()

Функция statistics.sum() также может использоваться для поиска среднего значения данных в списке Python.

Читайте также:  Css эффект матового стекла

Функция statistics.len() используется для вычисления длины списка, т.е. количества элементов данных, присутствующих в списке.

Кроме того, функция statistics.sum() используется для вычисления суммы всех элементов данных в списке.

Примечание: среднее значение = (сумма) / (количество).

from statistics import mean inp_lst = [12, 45, 78, 36, 45, 237.11, -1, 88] sum_lst = sum(inp_lst) lst_avg = sum_lst/len(inp_lst) print("Average value of the list:\n") print(lst_avg) print("Average value of the list with precision upto 3 decimal value:\n") print(round(lst_avg,3))
Average value of the list: 67.51375 Average value of the list with precision upto 3 decimal value: 67.514

3. Использование reduce() и lambda()

Мы можем использовать функцию reduce() вместе с функцией lambda().

Функция reduce() в основном используется для применения определенной (входной) функции к набору элементов, переданных в функцию.

reduce(function,input-list/sequence)
  • Первоначально функция reduce() применяет переданную функцию к первым двум последовательным элементам и возвращает результат.
  • Далее мы применяем ту же функцию к результату, полученному на предыдущем шаге, и к элементу, следующему за вторым элементом.
  • Этот процесс продолжается, пока не дойдет до конца списка.
  • Наконец, результат возвращается на терминал или экран в качестве вывода.

Функция lambda() используется для создания и формирования анонимных функций, то есть функции без имени или подписи.

from functools import reduce inp_lst = [12, 45, 78, 36, 45, 237.11, -1, 88] lst_len= len(inp_lst) lst_avg = reduce(lambda x, y: x + y, inp_lst) /lst_len print("Average value of the list:\n") print(lst_avg) print("Average value of the list with precision upto 3 decimal value:\n") print(round(lst_avg,3))
Average value of the list: 67.51375 Average value of the list with precision upto 3 decimal value: 67.514

Функция operator.add() для поиска среднего значения списка

Модуль operator.add() содержит различные функции для эффективного выполнения основных вычислений и операций.

Функцию operator.add() можно использовать для вычисления суммы всех значений данных, присутствующих в списке, с помощью функции reduce().

Примечание: среднее значение = (сумма) / (длина или количество элементов)

from functools import reduce import operator inp_lst = [12, 45, 78, 36, 45, 237.11, -1, 88] lst_len = len(inp_lst) lst_avg = reduce(operator.add, inp_lst) /lst_len print("Average value of the list:\n") print(lst_avg) print("Average value of the list with precision upto 3 decimal value:\n") print(round(lst_avg,3))
Average value of the list: 67.51375 Average value of the list with precision upto 3 decimal value: 67.514

Метод NumPy average() для вычисления среднего значения списка

Модуль NumPy имеет встроенную функцию для вычисления среднего значения элементов данных, присутствующих в наборе данных или списке.

Метод numpy.average() используется для вычисления среднего значения входного списка.

import numpy inp_lst = [12, 45, 78, 36, 45, 237.11, -1, 88] lst_avg = numpy.average(inp_lst) print("Average value of the list:\n") print(lst_avg) print("Average value of the list with precision upto 3 decimal value:\n") print(round(lst_avg,3))
Average value of the list: 67.51375 Average value of the list with precision upto 3 decimal value: 67.514

Источник

4 Ways to Find Average of List in Python: A Complete Guide

For instance, let’s calculate an average of a list of numbers:

grades = [4, 3, 3, 2, 5] average = sum(grades) / len(grades) print(f"The average is ")

This is a comprehensive guide to calculating the average of a list in Python. In this guide, you learn four separate ways for calculating averages.

4 Ways to Calculate the Average of a List in Python

Let’s take a closer look at four different ways to calculate the average of a list in Python.

1. The For Loop Approach

A python for loop that calculates the average of a list

The basic way to calculate the average of a list is by using a loop.

In this approach, you sum up the elements of the list using a for loop. Then you divide the sum by the length of the list.

For example, let’s calculate the average of grades using a for loop:

grades = [4, 3, 3, 2, 5] sum = 0 for number in grades: sum += number average = sum / len(grades) print(f"The average is ")

2. Statistics mean() Function

A script that calculates the average of a Python list using mean() function

Python has a built-in library called statistics. This library provides basic functionality for mathematics in statistical analysis.

One of the useful functions provided by the statistics library is the mean() function. You can use it to calculate the average for a list.

from statistics import mean grades = [4, 3, 3, 2, 5] average = mean(grades) print(f"The average is ")

3. NumPy mean() Function

Numpy mean() function to calculate list average in Python

NumPy is a commonly used Python library in data science. It provides you with powerful numerical computing tools and multi-dimensional arrays.

This library has also its own implementation of the mean() function.

To use it, first install NumPy by running the following command in your command line window:

With Numpy installed, you can use the mean() function to calculate the average of a list:

from numpy import mean grades = [4, 3, 3, 2, 5] average = mean(grades) print(f"The average is ")

Notice that installing and using the mean() function from NumPy is overkill if you’re never going to use the NumPy library again. But if you’re already using it in your project, then calculating the average with it might make sense.

4. reduce() Function in Python

Using the reduce() function to calculate average of a list in Python

Python’s functools library has a function called reduce(). You use this function when computing the average of a list by calculating the sum of the list.

Notice that using reduce in Python isn’t recommended anymore as better solutions exist. Make sure to read my article about the reduce() function to understand how it works and why it’s not used anymore.

Anyway, for the sake of demonstration, let’s use the reduce() function to calculate the average of a list:

from functools import reduce grades = [4, 3, 3, 2, 5] average = reduce(lambda x, y: x + y, grades) / len(grades) print(f"The average is ")

The reduce() function works by applying an operation on two elements of a list. It remembers the result and applies the operation to the next element and the result. It does this to accumulate a result for the whole list.

The operation in this example is the lambda expression lambda x, y: x + y. This is nothing but a function that takes two arguments x and y and returns the sum.

When we call reduce() on a list using this lambda, we tell it to sum up the numbers of a list.

Further Reading

Источник

Python: Find Average of List or List of Lists

Python Average of List Cover Image

In this post, you’ll learn how to use Python to find the average of a list, as well as of a list of list. You’ll learn how to do this using built-in methods like for-loops, the numpy library, and the statistics library.

The Python Average is calculated by adding up the items in a list and dividing it by the number of items in that list (which can be found using the length of that list).

How can you calculate an average in Python?

Calculating the average of different values in Python is very straightforward. You simply add up an array of numbers and divide it by the length of that array.

One naive way that you can calculate the average in Python is using a for loop.

Let’s see how this can be done:

# Calculating the average of list using a for loop numbers = [1,2,3,4,5,6,7,8,9] sum = 0 count = 0 for number in numbers: sum += number count += 1 average = sum / count print(average) # Returns: 5.0

This is a fairly labour-intensive way of calculating an average in Python, but it shows how it can be done.

Calculate Average of Python List using sum and len

Python doesn’t have a built-in function to calculate an average of a list, but you can use the sum() and len() functions to calculate an average of a list.

In order to do this, you first calculate the sum of a list and then divide it by the length of that list. Let’s see how we can accomplish this:

# Calculating the average of a list using sum() and len() numbers = [1,2,3,4,5,6,7,8,9] average = sum(numbers) / len(numbers) # Returns 5.0

If you find yourself doing this frequently in a script, you can turn this into a function. That way you can pass in any list and return its average. let’s see how to do this:

# Creating a function to calculate an average of a list numbers = [1,2,3,4,5,6,7,8,9] def average_of_list(list_to_use): return sum(list_to_use) / len(list_to_use) print(average_of_list(numbers)) # Returns: 5.0

In the example above, you turned the simple calculation of dividing the sum of a list by its length into a function to make it re-usable throughout your scripts.

Calculate Average of Python List using Numpy

If you’re working with numbers, chances are you’re using numpy in your script, meaning you can easily use some of its built-in functions. Numpy comes built-in with a number of mathematical functions that make it easy to calculate various statistics, such as an average.

Let’s see how we can work with numpy to calculate the average of a list:

# Using numpy to calculate the average of a list from numpy import mean numbers = [1,2,3,4,5,6,7,8,9] average = mean(numbers) print(average) # Returns: 5.0

Let’s see what we’ve done here:

  1. We imported mean from numpy, which is a function used to calculate the mean
  2. We then load our list numbers
  3. We then create a new variable and use the mean function, passing in the list as the argument

Next, let’s see how we can calculate the average of a Python list using the statistics library.

Find Average of List Using the Statistics Library

The statistics library is a Python library that lets you calculate, well, statistics. Similar to numpy, the statistics library has a mean function built into it. Let’s see how we can use this function to calculate the mean of a Python list:

# Using the statistics library to calculate a mean of a list from statistics import mean numbers = [1,2,3,4,5,6,7,8,9] average = mean(numbers) print(average) # Returns: 5.0

Let’s see what we accomplished here:

  1. We imported the mean() function from the statistics library
  2. We loaded in our list of numbers
  3. We passed this list in as an argument to the mean() function

Find Average of Python List of Lists

There may be many times when you want to calculate the average of a list of lists.

But first: what is a list of lists? A list of list is, simply, a list that contains other lists.

Let’s say you’re given a list of list like below:

list_of_lists = [ [1,2,3], [4,5,6], [7,8,9] ]

And you wanted to turn it into this:

row_averages = [2.0, 5.0, 8.0] column_averages = [4.0, 5.0, 6.0]

Use Zip to Calculate the Average of a List of Lists

We can use the Python zip() function to calculate the average of a list of lists. To learn more about the zip() function, check you my tutorial here. We can use the zip() function in conjunction with list comprehensions, which you can learn about in my video here:

Источник

Оцените статью