python - Python中没有重复的排列

标签 python python-itertools

我有 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],
]

关于python - Python中没有重复的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43816965/

相关文章:

python - 检查Boto3版本

python - MapReduce:使用Mrjob在网络图中查找三角形

python - Python 中正向替换的数值稳定性

python - 将数组中的数字簇分组

python - MaxProductOfThree 如何提高性能

python - 设置所有子图中刻度的大小

python - 如何垂直显示列表?

获取 3d 矩阵所有唯一阶乘组合的 Pythonic 方法

python - Python itertools.islice 的源代码在哪里?

python - 将 itertools.product() 结果附加到 Python 中的变量