亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

字典列表的聚合

字典列表的聚合

智慧大石 2021-11-23 19:45:11
我正在嘗試對我在我正在處理的 django 應用程序中找到的這些數據進行排序和聚合。問題是我迷失了遍歷列表和存儲數據的最佳方式。這是我所擁有的一個例子:from score.models import LocDataq = [        {'ref': '002', 'loc': 'seattle', 'total': '200'},         {'ref': '002', 'loc': 'seattle', 'total': '100'},         {'ref': '123', 'loc': 'dallas', 'total': '100'},         {'ref': '452', 'loc': 'cleveland', 'total': '600'},         {'ref': '123', 'loc': 'dallas', 'total': '200'},         {'ref': '002', 'loc': 'seattle', 'total': '300'}        ]我想最終得到的是下面的列表,它由 ref 字段聚合并使用 loc 維護此字段,但添加了 total 字段。這是所需的輸出。q = [        {'ref': '002', 'loc': 'seattle', 'total': '600'},         {'ref': '123', 'loc': 'dallas', 'total': '300'},         {'ref': '452', 'loc': 'cleveland', 'total': '600'},         ]有人能告訴我我有哪些工具可以做到這一點嗎?提前致謝!
查看完整描述

2 回答

?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

可以先構造一個中間字典,然后根據所需的輸出對其進行轉換:


from collections import defaultdict


q = [

        {'ref': '002', 'loc': 'seattle', 'total': '200'}, 

        {'ref': '002', 'loc': 'seattle', 'total': '100'}, 

        {'ref': '123', 'loc': 'dallas', 'total': '100'}, 

        {'ref': '452', 'loc': 'cleveland', 'total': '600'}, 

        {'ref': '123', 'loc': 'dallas', 'total': '200'}, 

        {'ref': '002', 'loc': 'seattle', 'total': '300'}

    ]


temp_dict = defaultdict(int)


for entry in q:

    temp_dict[(entry['ref'], entry['loc'])] += int(entry['total'])


result = [{'ref': k[0], 'loc': k[1], 'total': str(v)} for k, v in temp_dict.items()]

print(result)


# [{'ref': '002', 'loc': 'seattle', 'total': '600'},

#  {'ref': '123', 'loc': 'dallas', 'total': '300'},

#  {'ref': '452', 'loc': 'cleveland', 'total': '600'}]


查看完整回答
反對 回復 2021-11-23
?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

您可以使用一個聚合collections.Counter:


from collections import Counter

from pprint import pprint


q = [

    {"ref": "002", "loc": "seattle", "total": "200"},

    {"ref": "002", "loc": "seattle", "total": "100"},

    {"ref": "123", "loc": "dallas", "total": "100"},

    {"ref": "452", "loc": "cleveland", "total": "600"},

    {"ref": "123", "loc": "dallas", "total": "200"},

    {"ref": "002", "loc": "seattle", "total": "300"},

]


counts = Counter()

for x in q:

    ref, loc, total = x["ref"], x["loc"], x["total"]

    counts[ref, loc] += int(total)


pprint(

    [

        {"ref": ref, "loc": loc, "total": str(total)}

        for (ref, loc), total in counts.items()

    ]

)

#[{'loc': 'seattle', 'ref': '002', 'total': '600'},

# {'loc': 'dallas', 'ref': '123', 'total': '300'},

# {'loc': 'cleveland', 'ref': '452', 'total': '600'}]


查看完整回答
反對 回復 2021-11-23
  • 2 回答
  • 0 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號