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]]
结果均值列表:
myoutput = [["chocolate", 0.5], ["egg", 0.45]]
1、使用字典(dict)和for循环实现
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)
或者
d = {} for lst in (mylist1, mylist2): for i, v in lst: d.setdefault(i, []).append(v) # 也可以使用 collections.defaultdict [[k, sum(v)/len(v)] for k, v in d.items() if len(v) > 1]
或者
d_list1 = dict(mylist1)
d_list2 = dict(mylist2)
[[k, (v+d_list2[k])/2] for k, v in d_list1.items() if k in d_list2]
#[['egg', 0.45], ['chocolate', 0.5]]
2、使用pandas实现
安装pandas:
pip install pandas
实现代码:
import pandas as pd
df1 = pd.DataFrame(mylist1)
df2 = pd.DataFrame(mylist2)
res = pd.merge(df1, df2, on=0)
res['mean'] = res.mean(axis=1)
res.drop(['1_x', '1_y'], 1, inplace=True)
res.values.tolist()
[['egg', 0.45], ['chocolate', 0.5]]