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

遍历字典列表筛选特定学科学生姓名的实现问题

筛选学生字典列表的解决方案

假设你的student_roster结构如下(类似的字典列表):

student_roster = [
    {"name": "Alice", "favorite_subject": "Math"},
    {"name": "Bob", "favorite_subject": "English"},
    {"name": "Charlie", "favorite_subject": "Science"},
    {"name": "Diana", "favorite_subject": "History"}
]

两种实现方式

  • 普通for循环:逐个遍历学生字典,判断科目符合要求后,提取姓名加入结果列表
stem = []
for student in student_roster:
    if student["favorite_subject"] in ("Math", "Science"):
        stem.append(student["name"])
  • 列表推导式(简洁版):用一行代码完成筛选与提取,Python中常用的写法
stem = [student["name"] for student in student_roster if student["favorite_subject"] in ("Math", "Science")]

关键注意点

你之前出错的核心是没有明确指定提取student["name"]字段:

  • 如果直接append(student)会把整个字典加入列表
  • 如果append(student.values())会把字典的所有值(比如姓名、科目等)以列表形式加入

运行上述代码后,stem的结果为:["Alice", "Charlie"],完全符合你需要筛选STEM学科学生姓名的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:01:14