mardi 9 août 2016

Python - getting the average of two dict lists?

Here I have two lists: "donlist" is a list of random donation amounts between $1 and $100, and "charlist" is a list of random charity numbers between 1 and 15. I used two "dict"'s: "totals" to calculate the total donation per charity, and "numdon" to calculate the number of donations per charity. I now have to find the average donation per charity. I tried dividing "totals" by "numdon", but the output is just a list of "1.0"'s. I think it's because the dict has the charity number as well as the total/number of donations in them. Please help me calculate the average donation per charity. Thank you!

from __future__ import division
import random
from collections import defaultdict
from pprint import pprint

counter = 0
donlist = []
charlist = []
totals = defaultdict(lambda:0)
numdon = defaultdict(lambda:0)

while counter != 100:
    d = round(random.uniform(1.00,100.00),2)
    c = random.randint(1,15)
    counter +=1
    donlist.append(d)
    donlist = [round(elem,2) for elem in donlist]
    charlist.append(c)
    totals[c] += d
    numdon[c] += 1

    if counter == 100:
        break

print('Charity \t\tDonations')
for (c,d) in zip(charlist,donlist):
    print(c,d,sep='\t\t\t')
print("\nTotal Donations per Charity:") 
pprint(totals)
print("\nNumber of Donations per Charity:")
pprint(numdon)

# The average array doesn't work; I think it's because the "totals" and "numdon" have the charity numbers in them, so it's not just two lists of floats to divide.
avg = [x/y for x,y in zip(totals,numdon)]
pprint(avg)




Aucun commentaire:

Enregistrer un commentaire