2016-08-10 7 views
0

私は2つのリストを持っています: "donlist"は$ 1から$ 100までのランダムな寄付金額のリストです。 "charlist"は1から15までのランダムな寄付番号のリストです。私は2つの "dict"慈善団体ごとの寄付の総額を計算するための「numdon」と、慈善団体ごとの寄付の数を計算する「numdon」です。私は今、慈善団体ごとの平均寄付を見つけなければなりません。私は "numdon"で "totals"を分割しようとしましたが、出力は "1.0"のリストに過ぎません。私はそれがディクテーションにはチャリティー番号とそれに含まれる寄付の合計数があるからだと思う。慈善団体の平均寄付額を計算してください。ありがとうございました!Python - 2つの辞書リストの平均を取得していますか?

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) 

答えて

3

あなたの問題を解決:

avg = [totals[i]/numdon[i] for i in numdon] 

理由

の辞書のPythonのリスト内包で、デフォルトの反復は辞書のキーになります。試してみてください:

l = {1: 'a', 2: 'b'} 
for i in l: 
    print(i) 
# output: 
# 1 
# 2 
+0

ありがとうございました!各寄付については、それが平均寄付額を上回る、下回る、または等しい場合にも印刷しなければなりません。あなたはこれを行う簡単な方法を知っていますか?時間がかかり過ぎても大丈夫です。ありがとう! – user6627144

+0

あなたはすでに 'donlist'と' avg'を持っているので、単純に 'donlist'をループすることができます:' '(ch、compare(don、avg [ch]))ここで、compareは、寄付金額と、平均以上の収益を上回る、下回る、または等しいと比較して実装すべき機能です。 –

+0

ありがとうございました!これを自分のコードに追加する作業をします。 – user6627144

関連する問題