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

如何用带if语句的List comprehension实现字典列表年龄筛选函数

解决方案:使用列表推导式筛选符合年龄要求的人员列表

以下是符合要求的完整代码实现:

people = [{"name": "John", "age": 12}, {"name": "Sam", "age": 36}, {"name": "Frank"}]
def filter_adults(people, minimum_age=18):       
    new_list = [person for person in people if 'age' in person and person['age'] > minimum_age]
    return new_list 

逻辑说明

  • 列表推导式通过两个条件实现筛选:
    • 'age' in person:先排除未包含年龄字段的人员(比如示例中的Frank)
    • person['age'] > minimum_age:再筛选出年龄超过指定阈值(默认18)的人员
  • 整个逻辑通过一行列表推导式完成,满足题目对实现方式的要求

内容的提问来源于stack exchange,提问作者doloresafwat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:20:33