Average values in list python

average of the list in Python

Actually, this is a part of a homework, but i don’t know how to solve it.

4 Answers 4

Accept the list as the function argument. If the list has one item, return that. Create two iterators from the list. Pop one item off one of the lists, zip them together, then find the averages of the zip results. Recurse.

In short, you’re finding the «running average» from a list of numbers.

Using recursion would be helpful here. Return the only element when «len(lst) == 1» otherwise, compute the running average and recurse.

There are two parts in this assignment. First, you need to transform lists like [-1, 4, 8, 1] to lists like [1.5, 3.66, 3] (find the running averages). Second, you need to repeat this process with the result of the running averages until your list’s length is 2 (or 1).

You can tackle the first problem (find the running averages) independently from the second. Finding the running average is simple, you first keep track of the running sum (e.g. if the list is [-1, 4, 8, 1] the running sum is [-1, 3, 11, 12]) and divide each elements by their respective running index (i.e. just [1, 2, 3, 4]), to get [-1/1, 3/2, 11/3, 12/4] = [-1, 1.5, 3.66, 3]. Then you can discard the first element to get [1.5, 3.66, 3].

The second problem can be easily solved using recursion. Recursion is just another form of looping, all recursive code can be transformed to a regular for/while-loops code and all looping code can be transformed to recursive code. However, some problems have a tendency towards a more «natural» solution in either recursion or looping. In my opinion, the second problem (repeating the process of taking running averages) is more naturally solved using recursion. Let’s assume you have solved the first problem (of finding the running average) and we have a function runavg(lst) to solve the first problem. We want to write a function which repeatedly find the running average of lst, or return the average when the lst’s length is 2.

Источник

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

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

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

Читайте также:  Java ldaps active directory

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

Для вычисления среднего значения списка в 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.

Функция 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 имеет встроенную функцию для вычисления среднего значения элементов данных, присутствующих в наборе данных или списке.

Читайте также:  String constants in enum java

Метод 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

Источник

Python – Find Average of values in a List

Lists are a very versatile data structure in Python. When working with a list of numbers, it can be helpful to know how to calculate the mean of list values quickly. For example, you have a list of test scores and want to know what the average score was for the test. In this tutorial, we will look at how to get the average of a list in Python with the help of some examples.

Get average of list values in Python

Average of values in a List

You can use a combination of Python sum() and len() functions to compute the mean of a list. Alternatively, you can also use methods defined in libraries such as statistics , numpy , etc. to get the average of a list of values.

Let’s look at the above-mentioned methods with the help of examples.

1. Mean of a list using sum() and len()

To compute the mean of a list, you can use the sum() function to get the sum of the values in the list and divide that with the length of the list returned from the len() function.

# create a list ls = [1,2,3,4] # average of list sum(ls) / len(ls)

We get 2.5 as the average for the list above list of values.

2. Using statistics library

You can also use the statistics standard library in Python to get the mean of a list. Pass the list as an argument to the statistics.mean() function.

import statistics # create a list ls = [1,2,3,4] # average of list statistics.mean(ls)

We get the same result as above.

For more on the statistics library, refer to its documentation.

3. Using numpy library

You can also use the numpy library to get the list average. Numpy has a number of useful functions for working with arrays in Python.

import numpy as np # create a list ls = [1,2,3,4] # average of list np.mean(ls)

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Читайте также:  's Dashboard

Источник

How to Find Average of List in Python

The Python Average function is used to find the average of given numbers in a list. The formula to calculate average in Python is done by calculating the sum of the numbers in the list divided by the count of numbers in the list.

The Python average of list can be done in many ways listed below:

Method 1: Python Average via Loop

In this example, we have initialized the variable sum_num to zero and used for loop. The for-loop will loop through the elements present in the list, and each number is added and saved inside the sum_num variable. The average of list Python is calculated by using the sum_num divided by the count of the numbers in the list using len() built-in function.

Code Example

def cal_average(num): sum_num = 0 for t in num: sum_num = sum_num + t avg = sum_num / len(num) return avg print("The average is", cal_average([18,25,3,41,5]))

Method 2: Python Average – Using sum() and len() built-in functions

In this example the sum() and len() built-in functions are used to find average in Python. It is a straight forward way to calculate the average as you don’t have to loop through the elements, and also, the code size is reduced. The average can be calculated with just one line of code as shown below.

Program Example

# Example to find average of list number_list = [45, 34, 10, 36, 12, 6, 80] avg = sum(number_list)/len(number_list) print("The average is ", round(avg,2))

Method 3: Python Average Using mean function from statistics module

You can easily calculate the “average” using the mean function from the statistics module. Example shown below

# Example to find the average of the list from statistics import mean number_list = [45, 34, 10, 36, 12, 6, 80] avg = mean(number_list) print("The average is ", round(avg,2))

Method 4: Average in Python Using mean() from numpy library

Numpy library is commonly used library to work on large multi-dimensional arrays. It also has a large collection of mathematical functions to be used on arrays to perform various tasks. One important one is the mean() function that will give us the average for the list given.

Code Example

# Example to find avearge of list from numpy import mean number_list = [45, 34, 10, 36, 12, 6, 80] avg = mean(number_list) print("The average is ", round(avg,2))
C:\pythontest>python testavg.py The average is 31.86

Summary

  • The formula to calculate average is done by calculating the sum of the numbers in the list divided by the count of numbers in the list.
  • The average of a list can be done in many ways i.e
    • Python Average by using the loop
    • By using sum() and len() built-in functions from python
    • Using mean() function to calculate the average from the statistics module.
    • Using mean() from numpy library

    Источник

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