Python itertools生成词表:如何从仅处理word_list[0]改为遍历全列表
词表生成功能调整实现
原逻辑仅硬编码使用word_list[0]作为基础词拼接字符组合,调整后可遍历word_list所有条目执行相同操作,需注意规避itertools.product一次性迭代器耗尽的问题,具体实现如下:
修改后的代码
import itertools char = input("Enter Char's to Combine with the Keyword: ") n = int(input("Number of Char's Added to Keyword (2-9) :")) wrdLst = [] # 遍历word_list所有条目作为基础词 for base_word in word_list: # 每个基础词单独生成字符组合迭代器,避免一次性迭代器无法复用的问题 for combo in itertools.product(char, repeat=n): wrdLst.append(base_word + "".join(combo) + '\n') save(wrdLst)
核心修改说明
- 移除原硬编码的
word_list[0]引用,新增外层循环遍历word_list全部条目 - 将
itertools.product调用移动到基础词遍历的内层:itertools.product返回的是一次性迭代器,仅能被遍历1次,若放在外层会导致第一个基础词遍历完所有组合后,后续基础词无法获取到字符组合 - 去掉冗余的
int(n)强转:n在输入时已转为整数,无需重复转换 - 优化循环变量命名(
i改为语义更清晰的combo),提升可读性
内容的提问来源于stack exchange,提问作者Mike Evans
相关产品推荐
相关产品推荐

