如何通过python中的列表推导来解决
[
{
"id": 1,
"cleaning_type": "Lite service",
"service_name": "Floors",
},
{
"id": 2,
"cleaning_type": "Lite service",
"service_name": "Bathrooms",
},
{
"id": 3,
"cleaning_type": "Lite service",
"service_name": "Kitchen",
},
{
"id": 4,
"cleaning_type": "Moving cleaning",
"service_name": "Kitchen Including All Appliances And Cabinets",
},
{
"id": 5,
"cleaning_type": "Moving cleaning",
"service_name": "Shift Products",
}
]
我希望它的格式如下:
[
{
id: 1,
cleaning_type: 'Lite service',
service_name: ['Floors', 'bathroom', 'kitchen'],
},
{
id: 2,
cleaning_type: 'Moving cleaning',
service_name: ['Kitchen Including All Appliances And Cabinets','Shift Products'],
},
]
我希望列表在第二种格式,如组明智。Service_name将显示在清洗类型下。
这是我能得到的最接近您想要的格式。我不明白你是怎么让第二项的id
=2
的,因为2
的id
的cleaning_type
是Lite service
。
值得注意的是,键必须是不可变类型。我只是直接使用字符串,而不是创建名为id
,cleaning_type
和service_name
的变量绑定到相同的字符串(注意在您的示例中缺少引号)
items = [
{
'id': 1,
'cleaning_type': 'Lite service',
'service_name': 'Floors',
},
{
'id': 2,
'cleaning_type': 'Lite service',
'service_name': 'Bathrooms',
},
{
'id': 3,
'cleaning_type': 'Lite service',
'service_name': 'Kitchen',
},
{
'id': 4,
'cleaning_type': 'Moving cleaning',
'service_name': 'Kitchen Including All Appliances And Cabinets',
},
{
'id': 5,
'cleaning_type': 'Moving cleaning',
'service_name': 'Shift Products',
}
]
items_by_type = {}
for item in items:
cleaning_type = item['cleaning_type']
# We have not yet come across this cleaning type before, so create a new dict
if cleaning_type not in items_by_type:
new_item = {}
new_item['id'] = item['id']
new_item['cleaning_type'] = cleaning_type
new_item['service_name'] = [item['service_name']] # Note: This is a list
items_by_type[cleaning_type] = new_item
# The dict already exists, so we only need to add the cleaning type to the list that was previously created
else:
items_by_type[cleaning_type]['service_name'].append(item['service_name'])
# Transform to a list, since you don't want the keys
items_by_type_as_list = [d for d in items_by_type.values()]
expected_result = [
{
'id': 1,
'cleaning_type': 'Lite service',
'service_name': ['Floors', 'Bathrooms', 'Kitchen'],
},
{
'id': 4,
'cleaning_type': 'Moving cleaning',
'service_name': ['Kitchen Including All Appliances And Cabinets', 'Shift Products'],
}
]
print(items_by_type_as_list == expected_result)
输出:
True