假设我们有一个产品列表,每个产品都有一个price属性。我们需要根据价格过滤产品,只显示价格在某个范围内的产品。
products = [
{'name': 'iPhone', 'price': 999},
{'name': 'iPad', 'price': 699},
{'name': 'MacBook', 'price': 1299},
{'name': 'Apple Watch', 'price': 299},
]
def filter_products(products, price_min, price_max):
return list(filter(lambda x: x['price'] >= price_min and x['price'] <= price_max, products))
result = filter_products(products, 500, 1000)
print(result)
# [{'name': 'iPhone', 'price': 999}, {'name': 'iPad', 'price': 699}]
result = [product for product in products if product['price'] >= 500 and product['price'] <= 1000]
print(result)
# [{'name': 'iPhone', 'price': 999}, {'name': 'iPad', 'price': 699}]
这两种方法都能够根据价格过滤产品,只显示价格在某个范围内的产品。