如何用Lambda与filter筛选非停产(discontinued=0)且单价>15的产品?
Hey there! Let's fix up that filter code and make it work properly. Your current attempt has a few syntax missteps—let's break down what went wrong, then show the correct approach.
What's Wrong with Your Current Code?
Your line print(list(filter(lambda x: x=0,>15,products))) has two key issues:
- Incorrect condition syntax: You can't separate multiple conditions with commas, and
x=0is an assignment (not a check for equality—use==instead). - Missing key access: You didn't specify that you're checking the
discontinuedandunit_priceattributes/keys of each product (I'm assuming each product is a dictionary or object with these fields).
Correct filter() + Lambda Implementation
Assuming each item in your products list is a dictionary (like {'discontinued': 0, 'unit_price': 22.5}), here's the fixed code:
# Filter to keep non-discontinued (discontinued=0) and unit_price >15.0 filtered_products = list(filter(lambda product: product['discontinued'] == 0 and product['unit_price'] > 15.0, products)) print(filtered_products)
Let's break this down:
lambda product: ...: This anonymous function takes each product from the list as input.product['discontinued'] == 0: Checks if the product is not discontinued (note the double equals==for equality checks).product['unit_price'] > 15.0: Ensures the unit price is above 15.0.and: Ensures both conditions must be true for the product to be kept.list(...): Converts the filter object (an iterator) into a concrete list you can print or use elsewhere.
A More Pythonic Alternative: List Comprehension
Many Python developers prefer list comprehensions over filter() + lambda because they're often more readable and easier to debug. Here's the same logic written this way:
filtered_products = [ product for product in products if product['discontinued'] == 0 and product['unit_price'] > 15.0 ] print(filtered_products)
This does exactly the same thing, but the syntax is more straightforward—you're explicitly saying "for each product in products, keep it if both conditions are met."
内容的提问来源于stack exchange,提问作者Chris Ged

