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

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

根據值組合字典

根據值組合字典

交互式愛情 2023-10-31 14:10:06
我有一個看起來像這樣的字典列表[{"Name": John, "Score": 1}, {"Name": John, "Score": 2}, {"Name": Steve, "Score": 3}, {"Name": Steve, "Score": 4}]我怎樣才能像這樣組合這些字典呢?[{"Name": John, "Score": [1,2]},{"Name": Steve, "Score": [3,4]}]
查看完整描述

2 回答

?
人到中年有點甜

TA貢獻1895條經驗 獲得超7個贊

lst = [{"Name": "John", "Score": 1}, {"Name": "John", "Score": 2}, {"Name": "Steve", "Score": 3}, {"Name": "Steve", "Score": 4}]


out = {}

for d in lst:

    out.setdefault(d['Name'], []).append(d['Score'])


out = [{'Name': k, 'Score': v} for k, v in out.items()]


print(out)

印刷:


[{'Name': 'John', 'Score': [1, 2]}, {'Name': 'Steve', 'Score': [3, 4]}]


查看完整回答
反對 回復 2023-10-31
?
largeQ

TA貢獻2039條經驗 獲得超8個贊

使用itertools


def combine(group):

    out = {}

    out['Name'] = group[0]['Name']

    score = []

    for sub in group:

        score.append(sub['Score'])

    out['Score'] = score

    return out


grouped = map(combine,[list(v) for k,v in groupby(x, lambda x: x['Name'])])

print(list(grouped))


[{'Name': 'John', 'Score': [1, 2]}, {'Name': 'Steve', 'Score': [3, 4]}]


查看完整回答
反對 回復 2023-10-31
  • 2 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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