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?
解决方案
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.