比较两个列表以找到平均值

时间:2012-11-13 02:36:42

标签: python python-3.x

该清单应该保留所有宣誓书和所有辉煌等的平均利润; 我认为你可以做到这一点的方式是与列表进行比较,例如第1年的列表对janurary,feb,march,...,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

2 个答案:

答案 0 :(得分:0)

您的问题很可能是for i in range(0, years)应更改为for i in range(0, years)。你可以用这几个月来做到这一点,但是用这些年来做正确的事情同样重要。

答案 1 :(得分:0)

在我看来,更好的数据结构可以帮助解决这个问题。很难说出你最好的选择是什么,但有一个建议可能是使用dictdefaultdict更容易):

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模块。)

相关问题