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

如何对比两个列表,为不存在元素设0并循环输出指定格式字典

实现方案

直接上可运行的代码,完全符合你的需求:

lst = ['IDP','Remote.CMD.Shell','log4j']
lst2 = ['IDP']

def get_match_dict(source, compare):
    match_dict = {}
    for item in source:
        match_dict[item] = 1 if item in compare else 0
    return match_dict

# 循环输出3次,第一次用lst2,后两次用空列表
for idx in range(3):
    compare_list = lst2 if idx == 0 else []
    result_dict = get_match_dict(lst, compare_list)
    # 按指定格式打印
    print("{")
    for k, v in result_dict.items():
        print(f"    {k}:{v},")
    print("}")

代码说明

  • 封装了get_match_dict函数,负责核心对比逻辑:遍历源列表lst的每个元素,判断是否存在于对比列表中,存在则赋值1,否则0,最终返回构建好的字典。
  • 循环部分控制输出次数:一共输出3次,第一次使用给定的lst2作为对比列表,后两次改用空列表,刚好对应你给出的期望输出格式。

运行结果

执行代码后会输出:

{
    IDP:1,
    Remote.CMD.Shell:0,
    log4j:0,
}
{
    IDP:0,
    Remote.CMD.Shell:0,
    log4j:0,
}
{
    IDP:0,
    Remote.CMD.Shell:0,
    log4j:0,
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:03:03