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

Python遍历月份列表匹配字典列表生成指定输出的实现问题

Python实现月份匹配生成指定结果

已知变量

a=['May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January', 'February']

b=[ {'actualscore1': 550, 'forecastedScore1': 33, 'unit': 'u2', 'account': 'a2', 'domain': 'd2', 'location': 'l2', 'year': 2021, 'month': 'October'},
{'actualscore1': 550, 'forecastedScore1': 34, 'unit': 'u1', 'account': 'A1', 'domain': 'd1', 'location': 'l1', 'year': 2021, 'month': 'November'}]

实现思路

先把字典列表b预处理为「月份-所需字段字典」的映射表,遍历a的时候直接查表即可,时间复杂度仅为O(n+m)(n为a的长度,m为b的长度),比双重循环匹配效率更高。

完整实现代码

# 预处理b生成月份映射表
month_mapping = {
    item['month']: {
        'actualscore1': item['actualscore1'],
        'forecastedScore1': item['forecastedScore1'],
        'month': item['month']
    } for item in b
}

# 遍历a生成结果
output = [month_mapping.get(month, 0) for month in a]

# 验证输出
print(output)

输出结果

[0, 0, 0, 0, 0, {'actualscore1': 550, 'forecastedScore1': 33, 'month': 'October'}, {'actualscore1': 550, 'forecastedScore1': 34, 'month': 'November'}, 0, 0, 0]

和需求完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:57:03