0

该列表应包含所有 1 月和所有 2 月的平均利润等;我认为你可以这样做的方法是与列表进行比较,例如第 1 年的列表对于 1 月、2 月、3 月、...、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
4

2 回答 2

0

It seems to me that a better data structure could help with this a good bit. It's hard to tell what your best bet will be, but one suggestion could be to use a dict (defaultdict is even easier):

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])

Of course, we could use a list instead of a dictionary, but the dictionary would allow you to use month names instead of numbers (which may be kind of nice -- and I bet you could get their names pretty easily from the calendar module.)

于 2012-11-13T02:46:42.317 回答
0

您的问题很可能for i in range(0, years)应该更改为for i in range(0, years). 您可以在几个月内正确地做到这一点,但在几年内正确地做到这一点同样重要。

于 2012-11-13T02:43:59.027 回答