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

如何将Python字典列表中指定键对应的值追加到新列表中?

代码修改解决方案

原有代码问题

  • 存储结果的列表n被定义在外层遍历循环内部,每遍历一个字典就会被重置为空,无法累计收集结果
  • 匹配到第一个符合条件的日期值后直接执行return终止程序,不会继续遍历后续字典

修正后代码

temperatures = [
    {
        'monday': 12,
        'wednesday': 13,
        'friday': 14
    },
    {
        'monday': 10,
        'friday': 12
    },
    {
        'tuesday': 10,
        'thursday': 11,
        'saturday': 12
    },
]

def average(temperatures, day):
    # 结果列表移到循环外初始化,仅创建一次
    res = []
    for temp_dict in temperatures:
        # 直接判断目标日期是否存在于当前字典中,无需遍历所有键值对,执行效率更高
        if day in temp_dict:
            res.append(temp_dict[day])
    # 全部遍历完成后再返回结果
    return res

print(average(temperatures, 'monday'))

运行说明

调用函数传入monday参数,输出结果为[12, 10],已经将所有指定日期的对应值收集到同一个列表中。如果后续需要计算平均值,可在返回前增加计算逻辑,示例如下:

# 计算平均温度的版本
def average(temperatures, day):
    res = []
    for temp_dict in temperatures:
        if day in temp_dict:
            res.append(temp_dict[day])
    # 处理无匹配值的情况,避免除以0报错
    return sum(res)/len(res) if res else 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:45:10