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

for i in range(0, years)あなたの問題は、に変更する必要がある可能性が最も高いですfor i in range(0, years)。これを月で正しく行いますが、年で正しく行うことも同様に重要です。

于 2012-11-13T02:43:59.027 に答える
0

より良いデータ構造がこれにかなり役立つように思えます。あなたの最善の策が何であるかを伝えるのは難しいですが、1つの提案は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。モジュールからかなり簡単に月の名前を取得できるはずです)。

于 2012-11-13T02:46:42.317 に答える