首页 > 解决方案 > Python根据对象属性将对象列表拆分为子列表

问题描述

我有这样一个清单:

original_list = [
    {
        amenity: "Parking",
        amount: 120,
        version: 1,
        percentage: 4,
        id: 1
    },
    {
        amenity: "Pool",
        amount: 300,
        version: 2,
        percentage: 10,
        id: 5,
    },
    {
        amenity: "Pool",
        amount: 200,
        version: 1,
        percentage: 10,
        id: 2
}]

因此,如您所见,列表中有两个对象具有便利设施“池”,我如何根据便利设施将此列表分解为更小的列表:

例如:

vlist_a = [{
    amenity: "Parking",
    amount: 120,
    version: 1,
    percentage: 4,
    id: 1
}]

list_b = [{
    amenity: "Pool",
    amount: 300,
    version: 2,
    percentage: 10,
    id: 5,
},
{
    amenity: "Pool",
    amount: 200,
    version: 1,
    percentage: 10,
    id: 2
}]

我的意图是,当我以这种方式对它们进行排序时,我可以使用 lambda 方程获得每个列表中版本最大的对象。

提前致谢

标签: pythonlistlambda

解决方案


对可变数量的变量使用字典

Pythonic 解决方案是使用collections.defaultdict

from collections import defaultdict

d = defaultdict(list)

for item in original_list:
    d[item['amenity']].append(item)

print(d['Pool'])

[{'amenity': 'Pool', 'amount': 300, 'id': 5, 'percentage': 10, 'version': 2},
 {'amenity': 'Pool', 'amount': 200, 'id': 2, 'percentage': 10, 'version': 1}]

print(d['Parking'])

[{'amenity': 'Parking', 'amount': 120, 'version': 1, 'percentage': 4, 'id': 1}]

我的意图是,当我以这种方式对它们进行排序时,我可以使用 lambda 方程获得每个列表中版本最大的对象。

max您可以为此任务使用字典理解:

res = {k: max(v, key=lambda x: x['version']) for k, v in d.items()}

{'Parking': {'amenity': 'Parking',
  'amount': 120,
  'id': 1,
  'percentage': 4,
  'version': 1},
 'Pool': {'amenity': 'Pool',
  'amount': 300,
  'id': 5,
  'percentage': 10,
  'version': 2}}

推荐阅读