对字符串指定索引字符进行去重全排列的优雅Python实现方法
优化实现方案
直接上更简洁且鲁棒性更好的实现:
from itertools import permutations def string_perms(s, indices): s_list = list(s) # 提取待排列的字符 perm_chars = [s_list[i] for i in indices] # 生成去重的全排列 unique_perms = set(permutations(perm_chars)) result = [] for perm in unique_perms: # 每次使用原始字符串的拷贝修改,避免脏数据 curr = s_list.copy() for pos, char in zip(indices, perm): curr[pos] = char result.append(''.join(curr)) return result
核心优化点
- 去掉了原有代码中反复修改同一个临时列表的逻辑,每次都基于原始字符串拷贝做修改,避免迭代过程中的数据污染,逻辑更安全
- 变量命名更语义化,可读性更高
- 兼容边界场景:当
indices为空时会直接返回包含原字符串的列表,符合预期 - 依然保留了自动去重逻辑,即使待排列的位置有重复字符,也不会返回重复的结果
如果追求极致的代码简洁度,也可以用列表推导式进一步压缩:
from itertools import permutations def string_perms(s, indices): base = list(s) return list({''.join([base[i] if i not in indices else p[indices.index(i)] for i in range(len(base))]) for p in permutations([base[i] for i in indices])})
注意:压缩版可读性较低,仅适合对代码长度有要求的场景,生产环境更推荐上方的完整实现。
测试用例验证:调用string_perms('test_world', [2,3]),返回结果为['test_world', 'tets_world'],和示例要求完全一致。
内容的提问来源于stack exchange,提问作者Andy
相关产品推荐
相关产品推荐

