-1

从以下数组中,如何计算日期在数组中出现的次数。输出应采用以下格式 [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]]
4

2 回答 2

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]]
于 2012-12-02T10:23:16.400 回答
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}
于 2012-12-02T10:34:45.090 回答