in my code I obtain two different lists from different sources, but I know they are in the same order. The first list ("names") contains a list of keys strings, while the second ("result_values") is a series of floats. I need to make the pair unique, but I can't use a dictionary as only the last value inserted would be kept: instead, I need to make an average (arithmetic mean) of the values that have a duplicate key.
Example of the wanted results:
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}
My only ideas involve multiple iterations and so far have been ugly... is there an elegant solution to this problem?
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)
I would use a dictionary anyways
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])
If you're concerned with large lists, then I would replace zip with izip from itertools.
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