以下是一个示例代码,演示了如何按类别筛选产品:
class Product:
def __init__(self, name, category):
self.name = name
self.category = category
# 创建一些产品示例
products = [
Product("Apple", "Fruit"),
Product("Banana", "Fruit"),
Product("Carrot", "Vegetable"),
Product("Tomato", "Vegetable"),
Product("Orange", "Fruit")
]
# 按类别筛选产品的函数
def filter_products_by_category(products, category):
filtered_products = []
for product in products:
if product.category == category:
filtered_products.append(product)
return filtered_products
# 调用函数并打印结果
filtered_products = filter_products_by_category(products, "Fruit")
for product in filtered_products:
print(product.name)
在上面的代码中,我们首先定义了一个Product
类,它具有name
和category
属性。然后,我们创建了一些产品示例,并将它们存储在名为products
的列表中。
接下来,我们定义了一个名为filter_products_by_category
的函数,它接受一个产品列表和一个类别作为参数。函数遍历产品列表,并将符合给定类别的产品添加到名为filtered_products
的新列表中。最后,函数返回filtered_products
列表。
最后,我们调用filter_products_by_category
函数,并将结果打印出来。在这个例子中,我们将类别设置为"Fruit",并打印出所有类别为"Fruit"的产品的名称。