2012-11-13 3 views
0

목록에는 모든 성안 및 모든 성격의 평균 이익이 있어야합니다. 내가 할 수 있다고 생각했던 방식으로는 1 년차 목록에 janurary, feb, march, ..., 12 월 등의 가치가있는 목록과 비교하는 것이었고 거기에서 12 년을 기준으로 평균 이익을 찾을 수있었습니다. 아직 일하지 않고 여기서 어디로 가야할지 모르겠습니다. 어떤 제안?두 목록을 비교하여 평균을 찾으십시오.

MONTHS = 12 
def average_profit(years): 
    assert years >= 0, "Years cannot be negative" 
    total = 0.0 
    monthly_average = 0.0 
    total_months = years * MONTHS 
    total_list = [] 
    average_list=[] 
    percentage_list = [] 
    for i in range(0, years): 
     yearly_total = 0.0 
     for j in range(1, 13): 
      monthly_profit = float(input("Please enter the profit made in month {0}: ".format(j)).strip()) 
      monthly_average = monthly_average + monthly_profit 
      month_average = monthly_average/j 
      total_list.append(monthly_profit) 
      average_list.append(month_average) 
      yearly_total = yearly_total + monthly_profit 
      total_percent = (monthly_profit/12)*100 
      percentage_list.append(total_percent) 
     print("Total this year was ${0:.2f}".format(yearly_total)) 
     total = total + yearly_total 
    average_per_month = total/total_months 
    return total, average_per_month, total_months, total_list, average_list,   percentage_list 

답변

0

귀하의 문제는 for i in range(0, years)for i in range(0, years)로 변경해야 가능성이 높습니다. 몇 달 동안이 작업을 올바르게 수행 할 수 있지만 몇 년 동안 올바르게 진행하는 것이 중요합니다.

+3

두 가지가 같은 것 같습니다 ..? –

0

더 나은 데이터 구조가 좋은 비트로 도움이 될 것 같습니다. 그것은 당신의 가장 좋은 방법이 될 것입니다 무엇을 말할 어렵지만, 한 가지 제안은 dict (defaultdict도 쉽게) 사용할 수 :

물론
from collections import defaultdict: 
d = defaultdict(list) 
for i in range(0,years): 
    for month in range(1,13) 
     d[month].append(float(input())) 

#now find the sum for each month: 
for i in range(1,13): 
    print sum(d[i])/len(d[i]) 

, 우리는 대신 사전의 목록을 사용할 수 있지만 사전 숫자 대신 월 이름을 사용할 수 있습니다. (어떤 종류가 좋을 수도 있습니다. 그리고 calendar 모듈에서 쉽게 이름을 얻을 수있을 것입니다.)

관련 문제