下面是一个示例代码,展示了如何按类别排列产品数组:
from collections import defaultdict
def arrange_products_by_category(products):
# 使用 defaultdict 创建一个空列表作为默认值
categories = defaultdict(list)
for product in products:
# 获取当前产品的类别
category = product['category']
# 将产品添加到对应类别的列表中
categories[category].append(product)
# 将类别排列的产品数组返回
return categories
# 示例产品数组
products = [
{'name': 'Product 1', 'category': 'Category A'},
{'name': 'Product 2', 'category': 'Category B'},
{'name': 'Product 3', 'category': 'Category A'},
{'name': 'Product 4', 'category': 'Category B'},
{'name': 'Product 5', 'category': 'Category C'}
]
# 按类别排列产品数组
arranged_products = arrange_products_by_category(products)
# 输出结果
for category, products in arranged_products.items():
print(f'{category}:')
for product in products:
print(f'- {product["name"]}')
输出结果为:
Category A:
- Product 1
- Product 3
Category B:
- Product 2
- Product 4
Category C:
- Product 5
以上代码使用了 defaultdict
来创建一个空列表作为默认值,以避免在添加产品到类别列表时进行额外的判断和初始化操作。然后,遍历产品数组,根据产品的类别将其添加到对应的类别列表中。最后,将按类别排列的产品数组返回,并按类别逐个打印出来。