如何对比两个列表,为不存在元素设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
相关产品推荐
相关产品推荐

