You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用itertools.permutations生成3位、4位及5位数字全排列?

解决方案

itertools.permutations 支持传入第二个可选参数指定排列的长度,你只需要遍历3、4、5三个长度,汇总对应结果即可。

基础版本(返回排列元组)

from itertools import permutations

result = []
for length in [3, 4, 5]:
    result.extend(permutations(range(1, 6), length))

print(result)

转整数版本(输出你示例中类似123、4321的整数格式)

from itertools import permutations

result = []
for length in [3, 4, 5]:
    for perm in permutations(range(1, 6), length):
        # 将排列元组拼接转为整数
        num = int(''.join(map(str, perm)))
        result.append(num)

print(result)

内容的提问来源于stack exchange,提问作者Dark Soul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:12:02