Python中有序遍历多结果并为组合分配唯一键的简洁实现方法
解决方案
核心思路
直接使用Python标准库itertools内置的排列组合能力替代手动嵌套循环,可灵活适配任意长度、任意唯一字符数量的生成需求,不会出现遗漏或重复问题。
实现代码
import itertools def generate_sequences( length: int, max_unique: int = 3, special_char_max_count: int = 1, # 第三种字符最多出现次数,默认符合需求设为1 dedupe_isomorphic: bool = True, # 是否删除111/222这类等价串 char_set: str = "012" # 可选字符集,替换为"ABC"即可输出字母格式 ): sequences = set() # 仅使用1种字符的场景 if max_unique >= 1: if dedupe_isomorphic: sequences.add(char_set[0] * length) else: for c in char_set: sequences.add(c * length) # 使用2种字符的场景 if max_unique >= 2: chars = char_set[:2] if dedupe_isomorphic else char_set for combo in itertools.combinations(chars, 2): # 生成长度为N、至少包含两种字符的所有排列 for seq_tuple in itertools.product(combo, repeat=length): if len(set(seq_tuple)) < 2: continue sequences.add("".join(seq_tuple)) # 使用3种字符的场景 if max_unique >= 3: chars = char_set if not dedupe_isomorphic else char_set[:3] special_char = chars[2] normal_chars = chars[:2] # 遍历特殊字符所有可能出现的位置 for pos in range(length): # 剩余位置用前两种字符填充 for rest_tuple in itertools.product(normal_chars, repeat=length-1): seq_list = list(rest_tuple[:pos]) + [special_char] + list(rest_tuple[pos:]) sequences.add("".join(seq_list)) # 生成最终字典:序列为键,唯一自增ID为值,可按需修改值的规则 seq_dict = {seq: idx for idx, seq in enumerate(sequences)} return seq_dict
使用示例
生成指定长度的序列字典
# 生成长度为2的符合要求的序列字典 seq_dict_len2 = generate_sequences(length=2) # 输出所有序列键 print("\n".join(seq_dict_len2.keys()))
输出结果完全匹配你给出的长度为2的预期序列,调整length参数即可生成对应长度的序列。
参数调整说明
- 修改
max_unique为2即可生成仅包含2种唯一字符的序列 - 将
char_set改为"ABC"即可输出字母格式的序列 - 将
dedupe_isomorphic设为False即可保留11/22这类等价序列 - 修改
special_char_max_count可调整第三种字符的最大出现次数
内容的提问来源于stack exchange,提问作者Jonathan Martin
相关产品推荐
相关产品推荐

