如何识别Python字典的键对应值中是否包含指定连续序列0,1,2,3
Python判断字典值列表是否包含指定连续序列并定位对应键的实现方法
核心实现逻辑
目标是判断列表中是否存在连续序列[0,1,2,3],首先排除长度小于4的列表,再依次截取列表中所有长度为4的子序列和目标对比即可。
完整可运行代码
mydir = { "p1":[0,0,1,1,2,2,3,3], # 不包含目标序列 "p2":[0,0,1,2,3,4,5], # 包含目标序列 "p3":[0,1] # 不包含目标序列 } target = [0,1,2,3] target_len = len(target) match_keys = [] for key, lst in mydir.items(): # 长度不足直接跳过 if len(lst) < target_len: continue # 遍历所有可能的子序列起始位置 for i in range(len(lst) - target_len + 1): if lst[i:i+target_len] == target: match_keys.append(key) break # 匹配到就退出当前列表的循环,避免重复添加 if match_keys: print(f"识别到符合条件的键:{','.join(match_keys)}") else: print("未识别到符合条件的键")
贴合题目给定if...else结构的写法
如果需要严格按照题目给出的代码结构编写,判断条件可以用生成器表达式实现:
mydir = { "p1":[0,0,1,1,2,2,3,3], # 不包含目标序列 "p2":[0,0,1,2,3,4,5], # 包含目标序列 "p3":[0,1] # 不包含目标序列 } target = [0,1,2,3] target_len = len(target) if any(len(lst) >= target_len and any(lst[i:i+target_len] == target for i in range(len(lst)-target_len+1)) for lst in mydir.values()): # 提取第一个匹配的键输出,需要获取全部匹配键可以换成列表推导式收集 match_key = next(key for key, lst in mydir.items() if len(lst)>=target_len and any(lst[i:i+target_len]==target for i in range(len(lst)-target_len+1))) print(f"识别成功,符合条件的键为:{match_key}") else: print("未识别到符合条件的键")
注意:如果存在多个符合条件的键,
next方法只会返回第一个匹配结果,需要获取全部匹配键可以将next替换为列表推导式[key for key, lst in ...]收集所有结果。
内容的提问来源于stack exchange,提问作者Thamra Devps
相关产品推荐
相关产品推荐

