猿问

Python:查找每个月的平均库存值

基本上,我有一个元组列表,其中包含数据和价格,例如:


[ ("2013-02-12", 200.0), ("2012-02-25", 300.0), ("2000-03-04", 100.0), ("2000-03-05", 50.0)]

该函数需要找到每个月的平均股票价值,然后返回一个元组列表,包括日期(月和年)和股票价格。就像是:


[(250.0, "02-2013"), (100.0, "03-2000"), (50.0, "03-2000")]

这是我到目前为止的代码:


def average_data(list_of_tuples = []):


    list_of_averages = []

    current_year_int = 2013

    current_month_int = 2

    sum_float = float()

    count = 0

    for dd_tuple in list_of_tuples:

        date_str = dd_tuple[0]

        data_float = dd_tuple[1]

        date_list = date_str.split("-")

        year_int = int(date_list[0])

        month_int = int(date_list[1])

        date_year_str = "Date: " + str(month_int) + "-" + str(year_int);



        if month_int != current_month_int:

            average_float = sum_float / count

            average_list = [date_year_str, average_float]

            average_tuple = tuple(average_list)

            list_of_averages.append(average_tuple)

            current_month_int = month_int

            sum_float += data_float



        sum_float += data_float

        count += 1

        current_month_int = month_int

        current_year_int = year_int



    return list_of_averages

它返回的是平均值,但不是正确的,也许不是全部?我尝试在互联网上查看示例,并询问我的助教(这是针对python类的),但无济于事。有人可以指出我正确的方向吗?


慕的地10843
浏览 208回答 4
4回答

富国沪深

让我们为您的示例添加一个重复的日期,以便我们实际上可以看到一些平均值:l = [ ("2013-02-12", 200.0), ("2012-02-25", 300.0), ("2000-03-04", 100.0), ("2000-03-05", 50.0), ("2013-02-12", 100.0)]“ 2013-02-12”出现两次,总计300.0,因此应平均为150.0我不知道您是否了解字典或更好的字典,defaultdict,但这就是我正在使用的东西。使用defaultdict,您可以在构造函数中指定如果找不到密钥应返回的内容:from collections import defaultdictd = default_dict(float) # we'll use this to keep a running sum per dated_count = default_dict(int) # this one will keep track of how many times the date shows up我们也可以使用collections.Counter来保持计数,但是我们必须在列表上进行额外的迭代,这对于庞大的列表来说对于速度来说并不是一个好方法。现在,您将要遍历列表,并使用日期作为键将值添加到字典中:for k,v in l:&nbsp; &nbsp; d[k] += v # add the value&nbsp; &nbsp; d_count[k] += 1 # increment the count因此,您现在应该有两个字典,如下所示:>>> ddefaultdict(<type 'float'>, {'2013-02-12': 300.0, '2012-02-25': 300.0, '2000-03-05': 50.0, '2000-03-04': 100.0})>>> d_countdefaultdict(<type 'int'>, {'2013-02-12': 2, '2012-02-25': 1, '2000-03-05': 1, '2000-03-04': 1})现在,由于两个字典具有相同的键,因此您可以遍历字典中的项目,然后将日期的值除以该日期的计数,从而得到按日期的平均值。for k,v in d.iteritems():&nbsp; &nbsp; d[k] /= d_count[k]现在,“ d”应包含按日期划分的最终平均值:>>> ddefaultdict(<type 'float'>, {'2013-02-12': 150.0, '2012-02-25': 300.0, '2000-03-05': 50.0, '2000-03-04': 100.0})>>> d['2013-02-12']150.0>>> for k,v in d.iteritems():print k, v2013-02-12 150.02012-02-25 300.02000-03-05 50.02000-03-04 100.0
随时随地看视频慕课网APP

相关分类

Python
我要回答