平均Python中两个配对列表的重复值

时间:2010-10-26 09:45:59

标签: python list

在我的代码中,我从不同的来源获得两个不同的列表,但我知道它们的顺序相同。第一个列表(“names”)包含键字符串列表,而第二个列表(“result_values”)是一系列浮点数。我需要使该对唯一,但我不能使用字典,因为只保留插入的最后一个值:相反,我需要制作具有重复键的值的平均值(算术平均值)。

想要的结果示例:

names = ["pears", "apples", "pears", "bananas", "pears"]
result_values = [2, 1, 4, 8, 6] # ints here but it's the same conceptually

combined_result = average_duplicates(names, result_values)

print combined_result

{"pears": 4, "apples": 1, "bananas": 8}

我唯一的想法涉及多次迭代,到目前为止一直很难看......这个问题有一个优雅的解决方案吗?

5 个答案:

答案 0 :(得分:5)

from collections import defaultdict
def averages(names, values):
    # Group the items by name.
    value_lists = defaultdict(list)
    for name, value in zip(names, values):
        value_lists[name].append(value)

    # Take the average of each list.
    result = {}
    for name, values in value_lists.iteritems():
        result[name] = sum(values) / float(len(values))
    return result

names = ["pears", "apples", "pears", "bananas", "pears"]
result_values = [2, 1, 4, 8, 6]
print averages(names, result_values)

答案 1 :(得分:3)

我会反正使用字典

averages = {}
counts = {}
for name, value in zip(names, result_values):
    if name in averages:
        averages[name] += value
        counts[name] += 1
    else:
        averages[name] = value
        counts[name] = 1
for name in averages:
    averages[name] = averages[name]/float(counts[name]) 

如果您关注大型列表,那么我会将zip替换为来自itertools的izip

答案 2 :(得分:3)

您可以使用Cumulative moving average计算平均值,只迭代列表一次:

from collections import defaultdict
averages = defaultdict(float)
count = defaultdict(int)

for name,result in zip(names,result_values):
    count[name] += 1
    averages[name] += (result - averages[name]) / count[name]

答案 3 :(得分:1)

我认为你要找的是itertools.groupby

import itertools

def average_duplicates(names, values):
  pairs = sorted(zip(names, values))
  result = {}
  for key, group in itertools.groupby(pairs, key=lambda p: p[0]):
    group_values = [value for (_, value) in group]
    result[key] = sum(group_values) / len(group_values)
  return result

另请参阅zipsorted

答案 4 :(得分:0)

>>> def avg_list(keys, values):
...     def avg(series):
...             return sum(series) / len(series)
...     from collections import defaultdict
...     d = defaultdict(list)
...     for k, v in zip(keys, values):
...             d[k].append(v)
...     return dict((k, avg(v)) for k, v in d.iteritems())
... 
>>> if __name__ == '__main__':
...     names = ["pears", "apples", "pears", "bananas", "pears"]
...     result_values = [2, 1, 4, 8, 6]
...     print avg_list(names, result_values)
... 
{'apples': 1, 'pears': 4, 'bananas': 8}

如果您想要浮点平均值,则可以avg()返回float(len(series))