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

如何用Python生成符合指定规则的64种组合两列表格?

问题原因
  • 你使用的itertools.combinations_with_replacement方法生成的是无序可重复组合,会忽略元素的排列顺序,比如(1,2,1)、(1,1,2)、(2,1,1)会被判定为同一个组合,所以最终仅得到20种结果,不符合你要求的「顺序不同算作不同结果」的场景。
  • 你需要的是有序、可重复抽取3个元素的全排列,总数量为4^3=64种,正好匹配你的需求。
调整方案

使用itertools.product方法生成笛卡尔积,它会保留元素的顺序,可直接生成你需要的第一列所有64种组合,再按照规则替换中间位生成第二列即可。

完整实现代码
import itertools as it

lst = [1,2,3,4]
# 生成第一列所有64种有序三元组
col1_list = list(it.product(lst, repeat=3))
print(f"第一列总数量:{len(col1_list)}") # 输出为64,符合要求

# 生成两列的所有结果
result = []
for col1 in col1_list:
    first, mid, last = col1
    # 中间位替换为列表内其他数字
    for new_mid in lst:
        if new_mid != mid:
            col2 = (first, new_mid, last)
            result.append((col1, col2))

# 打印前10行验证效果
print("column 1  column 2")
for item in result[:10]:
    print(f"{''.join(map(str, item[0])):>8}  {''.join(map(str, item[1])):>8}")
运行效果示例
第一列总数量:64
column 1  column 2
     111       121
     111       131
     111       141
     112       122
     112       132
     112       142
     113       123
     113       133
     113       143
     114       124

和你给出的示例效果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:48:04