Python如何生成所有3位数字组合 现有代码仅输出999如何解决
Python生成000-999三位序列仅输出999的修复方案
问题表现
编写Python脚本目标是按顺序输出000、001、002……一直到999的所有3位数字序列,运行现有代码仅输出结果999;注释convert函数后可输出[0, 0, 0]、[0, 0, 1]格式的数字列表。
原有错误代码如下:
from itertools import product list = [x for x in range(0, 10) if True] for x in product(list, repeat=3): list3 = list(x) def convert(l): c = [str(i) for i in l] list2 = int("".join(c)) return(list2) print(convert(list3))
错误原因
- 核心逻辑位置错误:
convert调用和print语句写在了for循环外部。for循环遍历product生成的所有三元组时,每次都会覆盖重写list3变量,循环执行结束后list3只会保留最后一次遍历的结果[9,9,9],因此最终只会输出999。 - 变量命名不规范:使用Python内置类型名
list作为自定义变量名,会覆盖内置的list()方法,属于容易触发隐性bug的写法。 - 输出格式不符合预期:现有
convert函数把拼接后的字符串转成int类型,会自动丢弃前导零,无法输出000、001这类带前导零的三位格式。
修正代码
把转换、输出逻辑移到for循环内部,调整变量命名,同时用格式化方法保留前导零即可:
from itertools import product # 替换掉和内置类型重名的变量名 num_list = list(range(10)) for num_tuple in product(num_list, repeat=3): # 拼接为字符串后补前导零,直接输出符合要求的三位序列 print(''.join(str(i) for i in num_tuple).zfill(3))
如果需要同时拿到整数格式的所有结果,可以在循环内做收集:
from itertools import product num_list = list(range(10)) all_nums = [] for num_tuple in product(num_list, repeat=3): num_int = int(''.join(str(i) for i in num_tuple)) all_nums.append(num_int) # 格式化输出保留三位前导零 print(f"{num_int:03d}")
内容的提问来源于stack exchange,提问作者5adenc3
相关产品推荐
相关产品推荐

