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

如何用Python生成9个0和9个1的所有不重复排列?

生成9个0和9个1的不重复排列

你的问题核心是permutations会把相同字符(比如多个0)当作独立元素处理,导致生成大量重复结果。要高效生成所有不重复的排列,最优方案是利用组合数选位置的思路,而非直接生成排列再去重。

方法一:用itertools.combinations选位置(推荐)

我们可以从18个位置中选出9个位置放置1,剩下的位置自动放0,每个位置组合对应唯一的排列,完全不会有重复。代码如下:

from itertools import combinations

# 初始化结果列表
unique_arrays = []
# 遍历所有9个1的位置组合
for ones_positions in combinations(range(18), 9):
    # 创建一个全0的列表
    current_array = [0] * 18
    # 在选中的位置设置为1
    for pos in ones_positions:
        current_array[pos] = 1
    unique_arrays.append(current_array)

# 验证结果数量,应等于组合数C(18,9)=48620
print(len(unique_arrays))

这种方法直接生成目标结果,无冗余计算,内存和时间效率远高于去重方式。

方法二:用集合去重(不推荐)

如果一定要用permutations,可以把生成的元组转成集合去重,但这种方法会先生成海量重复元素(18!个,远大于48620),内存和时间消耗极大,仅作参考:

from itertools import permutations

# 生成所有排列后转集合去重
raw_perms = permutations('0'*9 + '1'*9, 18)
unique_perms = set(raw_perms)
# 转成列表的列表
unique_arrays = [list(p) for p in unique_perms]

print(len(unique_arrays))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 14:21:15