Personally I'd do it using a dictionary structure, and by using zip to iterate both lists simultaneously:
years = [1982, 1983, 1984, 1985, 1982, 1983, 1984, 1985, 1982, 1983, 1984, 1985]
amount = [100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400]
results = {}
for y, a in zip(years,amount):
if y in results:
results[y] += a
else:
results[y] = a
for year, total in results.items():
print(str(year) + ": " + str(total))
That way you can easily access each year and it's amount by going results[year]
to get the corresponding amount.
Also I renamed Years
and Amounts
to years
and amounts
because it's convention to use lowercase first letters on variables in Python.
To avoid the test to see if a key is in the results
dictionary (the if statement), you could also use a defaultdict structure:
import collections
years = [1982, 1983, 1984, 1985, 1982, 1983, 1984, 1985, 1982, 1983, 1984, 1985]
amount = [100, 200, 300, 400, 100, 200, 300, 400, 100, 200, 300, 400]
results = collections.defaultdict(int)
for y, a in zip(years,amount):
results[y] += (a)
for year, total in results.items():
print(str(year) + ": " + str(total))