python - 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 方程获得每个列表中版本最大的对象。
提前致谢
解决方案
对可变数量的变量使用字典
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}}
推荐阅读
- android-motionlayout - 带有 recyclerView 的 Motionlayout 不稳定
- swift - textView 和键盘之间的空间
- flutter - 如何使 StarRating 小部件对齐左侧
- ios - 如何使用委托和协议快速编辑和传回单元格数据
- php - 我无法将条形码图像保存到文件夹中,我保存信息后一直黑屏
- c - 宏内容的长度是否有限制?
- java - 项目开始运行时如何检查文件是否存在?
- c# - Unity 中的 2D 角色不跳跃问题
- javascript - 在柱形图上显示负值的另一种方法
- javascript - 是否可以在数组中包含 Getter/Setter?