Home > database >  finding the element in a list closest to the mean of elements in python?
finding the element in a list closest to the mean of elements in python?

Time:09-21

This is my array a= [5, 25, 50, 100, 250, 500] . The mean value of a is 155 (i calculated using sum(a)/len(a)) but i have to store 100 in a variable instead of 155.

Is there any easy way to solve this problem.

CodePudding user response:

IIUC, use numpy.argmin to find the the index of the value closest to the mean by computing the absolute difference to the mean:

a = np.array([5, 25, 50, 100, 250, 500])

out = a[np.argmin(np.abs(a-a.mean()))]

output: 100

CodePudding user response:

If you want to keep it pure python, you can use a custom key for sorted to find the lowest difference element:

a= [5, 25, 50, 100, 250, 500]
a_mean = sum(a)/len(a)
out = sorted(a, key=lambda val:abs(val-a_mean))[0]
# 100

CodePudding user response:

If we want to go with pure python, I would write a function like this:

from typing import List
numb_list = [1, 4, 10, 20, 55, 102, 77, 89]


def find_closest_to_mean(num_list: List[int])->int:
    mean = sum(numb_list)/len(num_list)
    distance_list = [abs(mean - num) for num in numb_list]
    return num_list[distance_list.index(min(distance_list))]


print(find_closest_to_mean(numb_list))  

[Out]

mean = 44.75
closest number = 55

here I create a function called find_closest_to_mean that expects a num_list argument that is a list of integers. It then first calculates the mean of the list, creates a distance_list in which each element corresponds to the distance of the num_list in that position with the mean (as an absolute value). lastly it returns an integer from the num_list that has the least distance to the mean.

  • Related