python count日期出现的次数

时间:2012-12-02 10:20:29

标签: python

从以下数组中,如何计算数组中出现次数的日期。输出应采用以下格式[date,count]

   new_dates =  [['2012-12-02', 14],['2012-12-03',2],....]

输入:

  dates = [['2012-12-02', 17], ['2012-12-01', 5], ['2012-12-02', 15], ['2012-12-02', 8], ['2012-12-02', 17], ['2012-12-02', 15], ['2012-12-11', 6], ['2012-12-02', 1], ['2012-12-02', 9], ['2012-12-02', 11], ['2012-12-03', 13], ['2012-12-03', 10], ['2012-12-02', 18], ['2012-12-02', 11], ['2012-12-02', 12], ['2012-12-05', 14], ['2012-12-02', 3], ['2012-12-02', 6], ['2012-12-06', 10], ['2012-12-07', 0], ['2012-12-08', 3], ['2012-12-09', 12], ['2012-12-02', 6]]

2 个答案:

答案 0 :(得分:3)

>>> from collections import Counter
>>> [[k,c[k]] for k in Counter([i[0] for i in dates])]
[['2012-12-01', 1], ['2012-12-02', 14], ['2012-12-03', 2], ['2012-12-05', 1], ['
2012-12-06', 1], ['2012-12-07', 1], ['2012-12-08', 1], ['2012-12-09', 1], ['2012
-12-11', 1]]

如果您无法使用计数器,请使用defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i in dates:
...    d[i[0]] += 1
...
>>> [[k,d[k]] for k in d]
[['2012-12-01', 1], ['2012-12-02', 14], ['2012-12-03', 2], ['2012-12-05', 1], ['
2012-12-06', 1], ['2012-12-07', 1], ['2012-12-08', 1], ['2012-12-09', 1], ['2012
-12-11', 1]]

答案 1 :(得分:0)

好的,如果不能使用Counter,我建议使用循环/计数解决方案:

使用Dict.get(a),如果Dict中没有键,则返回None,如果dict中有“a”键,则返回值

>>> dates = [['2012-12-02', 17], ['2012-12-01', 5], ['2012-12-02', 15], ['2012-12-02', 8], ['2012-12-02', 17], ['2012-12-02', 15], ['2012-12-11', 6], ['2012-12-02', 1], ['2012-12-02', 9], ['2012-12-02', 11], ['2012-12-03', 13], ['2012-12-03', 10], ['2012-12-02', 18], ['2012-12-02', 11], ['2012-12-02', 12], ['2012-12-05', 14], ['2012-12-02', 3], ['2012-12-02', 6], ['2012-12-06', 10], ['2012-12-07', 0], ['2012-12-08', 3], ['2012-12-09', 12], ['2012-12-02', 6]]
>>> dict_ = {}
>>> for i,j in dates:
     if dict_.get(i):
         dict_[i] += 1
     else:
         dict_[i] = 1

>>> dict_
{'2012-12-01': 1, '2012-12-02': 14, '2012-12-03': 2, '2012-12-05': 1, '2012-12-06': 1, '2012-12-07': 1, '2012-12-08': 1, '2012-12-09': 1, '2012-12-11': 1}