Skip to main content
 首页 » 编程设计

python之Python中没有重复的排列

2025年05月04日9thcjp

我有 N 个位置,每个位置可以是 0 或 1。我有固定数量的 1,我想在这 N 个位置中排列这些固定数量的 1。

from itertools import permutations 
p = [0 for k in xrange(6)] 
for k in xrange(0,3): 
        p[k] = 1 
print(list(permutations(p))) 

但上面的结果在列表中包含四个 [0,0,0,1,1,1]。我只想要其中之一。我怎样才能摆脱这些重复?

请您参考如下方法:

您可以改为获取 1 的位置:

from itertools import combinations 
 
 
def place_ones(size, count): 
    for positions in combinations(range(size), count): 
        p = [0] * size 
 
        for i in positions: 
            p[i] = 1 
 
        yield p 

在行动中:

>>> list(place_ones(6, 3)) 
[ 
    [1, 1, 1, 0, 0, 0], 
    [1, 1, 0, 1, 0, 0], 
    [1, 1, 0, 0, 1, 0], 
    [1, 1, 0, 0, 0, 1], 
    [1, 0, 1, 1, 0, 0], 
    [1, 0, 1, 0, 1, 0], 
    [1, 0, 1, 0, 0, 1], 
    [1, 0, 0, 1, 1, 0], 
    [1, 0, 0, 1, 0, 1], 
    [1, 0, 0, 0, 1, 1], 
    [0, 1, 1, 1, 0, 0], 
    [0, 1, 1, 0, 1, 0], 
    [0, 1, 1, 0, 0, 1], 
    [0, 1, 0, 1, 1, 0], 
    [0, 1, 0, 1, 0, 1], 
    [0, 1, 0, 0, 1, 1], 
    [0, 0, 1, 1, 1, 0], 
    [0, 0, 1, 1, 0, 1], 
    [0, 0, 1, 0, 1, 1], 
    [0, 0, 0, 1, 1, 1], 
]