4 回答

TA贡献1790条经验 获得超9个赞
让我们为您的示例添加一个重复的日期,以便我们实际上可以看到一些平均值:
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 defaultdict
d = default_dict(float) # we'll use this to keep a running sum per date
d_count = default_dict(int) # this one will keep track of how many times the date shows up
我们也可以使用collections.Counter来保持计数,但是我们必须在列表上进行额外的迭代,这对于庞大的列表来说对于速度来说并不是一个好方法。
现在,您将要遍历列表,并使用日期作为键将值添加到字典中:
for k,v in l:
d[k] += v # add the value
d_count[k] += 1 # increment the count
因此,您现在应该有两个字典,如下所示:
>>> d
defaultdict(<type 'float'>, {'2013-02-12': 300.0, '2012-02-25': 300.0, '2000-03-05': 50.0, '2000-03-04': 100.0})
>>> d_count
defaultdict(<type 'int'>, {'2013-02-12': 2, '2012-02-25': 1, '2000-03-05': 1, '2000-03-04': 1})
现在,由于两个字典具有相同的键,因此您可以遍历字典中的项目,然后将日期的值除以该日期的计数,从而得到按日期的平均值。
for k,v in d.iteritems():
d[k] /= d_count[k]
现在,“ d”应包含按日期划分的最终平均值:
>>> d
defaultdict(<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, v
2013-02-12 150.0
2012-02-25 300.0
2000-03-05 50.0
2000-03-04 100.0
添加回答
举报