您可以尝试使用熊猫:
import pandas as pd
list_1 = [2,241,21,512,142]
list_2 = ['a','b','a','a']
c = pd.DataFrame()
c['list_1'] = list_1
c['list_2'] = list_2
uniques = c.list_2.unique()
for i in uniques:
print('sum ' + i + ': ' + str(c[c.list_2==i].list_1.sum()))
print('mean ' + i + ': ' + str(c[c.list_2==i].list_1.mean()))
,
让我们假设您所描述的list1 = [2,142]
和list2 = ['a','a']
。我不知道您要使用的确切约束是什么,但是除了初始设置之外,让我使用两个字典。
- 在
list2
中获取唯一的密钥,并计算密钥的数量。
让我们定义一个空字典cnt_dic
来计算键的数量。完成键计数后,创建零值字典res_dic
的副本。
cnt_dic = {}
for key in list2:
if key not in cnt_dic:
cnt_dic[key] = 1
else:
cnt_dic[key] += 1
res_dic = cnt_dic.copy()
for key in res_dic.keys():
res_dic[key] = 0
- 使用收集的键对整数求和。
for num,key in zip(list1,list2):
res_dic[key] += num
- 计算平均值。
for key in cnt_dic.keys():
res_dic[key] /= cnt_dic[key]
然后res_dic
将包含{'a': 55.0,'b': 376.5}
。
本文链接:https://www.f2er.com/3140621.html