-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

OK、カウンターを使用できない場合は、ループ/カウント ソリューションをお勧めします。

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 に答える