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.
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.
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.
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.
Python3. The inbuilt function mean() can be used to calculate the mean( average ) of the list.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With