You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Lambda与filter筛选非停产(discontinued=0)且单价>15的产品?

Filtering Products: Keep Only Non-Discontinued Items with Unit Price > 15.0

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:

  1. Incorrect condition syntax: You can't separate multiple conditions with commas, and x=0 is an assignment (not a check for equality—use == instead).
  2. Missing key access: You didn't specify that you're checking the discontinued and unit_price attributes/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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:50:13