Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently get the mean of the elements in two list of lists in Python

Tags:

python

list

mean

I have two lists as follows.

mylist1 = [["lemon", 0.1], ["egg", 0.1], ["muffin", 0.3], ["chocolate", 0.5]] mylist2 = [["chocolate", 0.5], ["milk", 0.2], ["carrot", 0.8], ["egg", 0.8]] 

I want to get the mean of the common elements in the two lists as follows.

myoutput = [["chocolate", 0.5], ["egg", 0.45]] 

My current code is as follows

for item1 in mylist1:     for item2 in mylist2:         if item1[0] == item2[0]:              print(np.mean([item1[1], item2[1]])) 

However, since there are two for loops (O(n^2) complexity) this is very inefficient for very long lists. I am wondering if there is more standard/efficient way of doing this in Python.

like image 580
EmJ Avatar asked May 10 '20 13:05

EmJ


People also ask

How do you take the average of two lists in Python?

The average value can be determined by the conventional sum() and len function of python and the extension of one to two lists can be dealt using the “+” operator.

How can you calculate the average of list items in Python?

Python mean() function mean() function is used to calculate the mean/average of input values or data set. The mean() function accepts the list, tuple or data-set containing numeric values as a parameter and returns the average of the data-items.

How do you compare two lists of elements in Python?

Using list.sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.

Can you take the mean of a list in Python?

Python3. The inbuilt function mean() can be used to calculate the mean( average ) of the list.


1 Answers

You can do it in O(n) (single pass over each list) by converting 1 to a dict, then per item in the 2nd list access that dict (in O(1)), like this:

mylist1 = [["lemon", 0.1], ["egg", 0.1], ["muffin", 0.3], ["chocolate", 0.5]] mylist2 = [["chocolate", 0.5], ["milk", 0.2], ["carrot", 0.8], ["egg", 0.8]]  l1_as_dict = dict(mylist1)  myoutput = [] for item,price2 in mylist2:     if item in l1_as_dict:         price1 = l1_as_dict[item]         myoutput.append([item, (price1+price2)/2])  print(myoutput) 

Output:

[['chocolate', 0.5], ['egg', 0.45]] 
like image 147
Adam.Er8 Avatar answered Oct 15 '22 20:10

Adam.Er8