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

如何在循环中跳过缺失条目?遍历字典匹配数据集不存在键时怎么处理

解法

你提供的示例代码本身存在几个问题:

  • 变量名拼写错误:定义的数据集变量为dataset,循环中错误写成了datasets
  • 遍历逻辑颠倒:应该先遍历日程字典中的人名,再校验人名是否存在于数据集,而非遍历数据集的键
  • 缩进错误:plt.plot写在continue之后,原本逻辑下永远不会被执行

核心实现逻辑:
遍历到每个目标人名时,先做存在性校验,仅当人名存在于数据集的键中时才执行绘图操作,不存在直接跳过即可。

完整可运行代码示例:

import matplotlib.pyplot as plt

# 日程字典
dictionary = {'Mon':['Mary','Suszie','Larry'],
              'Tue':['Sam','Ola','Chris'],
              'Wed':['Tanner','Ram','Dustin']}

# 数据集
dataset = {'Mary':[1,4,6,2,7],
           'Suszie':[9,2,6,4,7],
           'Max':[1,3,1,3,5]}

# 遍历逻辑
for name_list in dictionary.values():
    for name in name_list:
        # 不存在则直接跳过
        if name not in dataset:
            continue
        # 存在则绘图
        plt.plot(dataset[name], label=name)

plt.legend()
plt.show()

如果不想写continue,也可以直接正向判断,逻辑更直观:

for name_list in dictionary.values():
    for name in name_list:
        if name in dataset:
            plt.plot(dataset[name], label=name)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:45:04