2016-08-10 3 views
0

여기에 두 개의 목록이 있습니다. "돈 목록"은 $ 1에서 $ 100 사이의 무작위 기부 금액 목록이고 "charlist"는 1에서 15 사이의 임의 자선 단체 번호 목록입니다. 두 개의 "dict" 자선 단체당 기부 총액을 계산하려면 "numdon", 자선 단체당 기부금 수를 계산하려면 "numdon"을 입력하십시오. 자선 단체당 평균 기부금을 찾아야합니다. 나는 "numdon"으로 "totals"을 나눠 봤지만 출력은 단지 "1.0"의 목록 일뿐입니다. 나는 그 자리에 자선 단체 번호와 기부금 총액이 있기 때문이라고 생각합니다. 자선 단체당 평균 기부액을 계산해주세요. 고맙습니다!Python - 두 개의 dict리스트 평균을 얻고 싶습니까?

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

이유 :

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

이 문제 해결

사전인가의 파이썬 지능형리스트에서를 기본 반복은 딕셔너리의 키에있을 것입니다. 사용해보기 :

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])) for ch, zip (charlist, donlist)]' 여기서 compare는 기부 금액 비교와 위, 아래 또는 동등한 평균 및 수익을 구현해야하는 기능입니다. –

+0

정말 고마워요! 나는 그것을 지금 코드에 추가하려고 노력할 것이다. – user6627144

관련 문제