我有包含多個類似時間戳的串列,我計算了它們的出現次數,如下面的代碼:
count = collections.Counter(MyList)
return [{"result": count}]
它給了我這樣的結果:
"2021-10-09T00:26:16": 10,
"2021-10-08T15:08:37": 5,
"2021-10-08T13:40:50": 6,
但我想要這樣的結果
{"timestamp": "2021-01-01T00:00:00", "count": 10},
{"timestamp": "2021-01-02T00:00:00", "count": 5},
{"timestamp": "2021-01-03T00:00:00", "count": 6},
uj5u.com熱心網友回復:
您可以使用 Dictionary Comprehension 來滿足要求。
count = collections.Counter(MyList)
result = [{'timestamp': k, 'count': v} for k,v in count.items()]
從PEP 274 - Dict Comprehensions 中了解有關 Dictionary Comprehension 的更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/321385.html
