【问题标题】:Python split a list of objects into sublists based on objects attributesPython根据对象属性将对象列表拆分为子列表
【发布时间】:2023-04-11 07:09:01
【问题描述】:

我有这样一个清单:

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 方程获得每个列表中版本最大的对象。

提前致谢

【问题讨论】:

    标签: python list lambda


    【解决方案1】:

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

    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}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2015-01-12
      • 2021-10-24
      • 2021-06-27
      相关资源
      最近更新 更多