python 列表套字典 根据相同的key分组

l = [[
    {"id": 1, "key": 255},
    {"id": 2, "key": 255},
    {"id": 3, "key": 256},
    {"id": 4, "key": 256},
    {"id": 4, "key": 256},
]]


def getResult_1(l):
    res = []
    keys = set([item[i]['key'] for item in l for i in range(0, len(item))])

    for ip in keys:
        tmp = []
        for ite in l:
            for i in range(0, len(ite)):
                if ip == ite[i]['key']:
                    tmp.append(ite[i])  # 追加列表
            res.append(tmp)
    return res


ret = getResult_1(l)
print(ret)

  

# 结果
[
[{'id': 3, 'key': 256}, {'id': 4, 'key': 256}, {'id': 4, 'key': 256}], 
[{'id': 1, 'key': 255}, {'id': 2, 'key': 255}]
]

  

  

原文地址:https://www.cnblogs.com/a438842265/p/13671185.html