在python中按组获取平均值

时间:2017-12-28 12:56:54

标签: python

输入是这样的:

G1: 12
G2: 15
G1: 9
G3: 18
G2: 17
G3: 6
G1: 20

输出应该是个别群体的平均值,如G1:12 + 9 + 20/3 = 13.67, G2:15 + 17/2 = 16,G3:6 + 18/2 = 12

2 个答案:

答案 0 :(得分:0)

为群组创建list词典:

groups = [{'G1': 12},
          {'G2': 15},
          {'G1': 9},
          {'G3': 18},
          {'G2': 17},
          {'G3': 6},
          {'G1': 20}]    

将价值观纳入其群组:

result = dict()

for d in groups:
    for k, v in d.items():
        if k in result:
            result[k].append(v)
        else:
            result[k] = [v]

按组计算平均值:

averages = []

for d in result:
    averages.append((d, sum(result[d]) / len(result[d])))

print(averages)

[('G1', 13.666666666666666), ('G2', 16.0), ('G3', 12.0)]
>>> 

答案 1 :(得分:0)

您可以将输入保存为.txt文件,然后您可以尝试这样的操作:

  

第一种方法:使用collections.defaultdict

import collections
track=collections.defaultdict(list)
with open('file.txt','r') as f:
    for line in f:
        key,value=line.split(':')
        track[key].append(int(value))


print(list(map(lambda x:(x,sum(track[x])/len(track[x])),track.keys())))

输出:

[('G3', 12.0), ('G1', 13.666666666666666), ('G2', 16.0)]
  

第二种方法:没有任何外部模块的纯逻辑

track={}
with open('file.txt','r') as f:
    for line in f:
        key,value=line.split(':')
        if key not in track:
            track[key]=[int(value)]
        else:
            track[key].append(int(value))

print(list(map(lambda x:(x,sum(track[x])/len(track[x])),track.keys())))

输出:

[('G1', 13.666666666666666), ('G2', 16.0), ('G3', 12.0)]