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

如何简化字典中多组值对的检查代码?

简洁实现方案

你可以把需要检查的键对整理成列表,结合any()函数和集合方法实现单条if判断,代码更简洁且便于后续扩展:

from collections import defaultdict

# 示例字典
my_dic = defaultdict(set)
my_dic["key1"] = {"a", "b", "elem1"}

# 定义所有需检查的键对集合
check_groups = [{"a", "b"}, {"a-foo", "b-foo"}, {"a-bar", "b-bar"}]
target_set = my_dic["key1"]

if any(group.issubset(target_set) for group in check_groups):
    print("Exists")

说明

  1. 统一管理检查组:把三组需要同时存在的键分别包装成集合存入check_groups,后续新增检查组直接往列表里追加即可。
  2. issubset高效判断:group.issubset(target_set)会直接验证当前组内的所有元素是否都存在于目标集合my_dic["key1"]中。
  3. any()简化逻辑:只要任意一组满足条件,any()就会返回True,触发后续打印操作。

如果偏好直接判断元素存在性,也可以用生成器表达式实现:

check_pairs = [("a", "b"), ("a-foo", "b-foo"), ("a-bar", "b-bar")]
target_set = my_dic["key1"]

if any(a in target_set and b in target_set for a, b in check_pairs):
    print("Exists")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 16:14:54