You need to enable JavaScript to run this app. Python itertools生成词表:如何从仅处理word_list[0]改为遍历全列表
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.29 23:54:01