python - 获取 numpy 数组的所有排列

标签 python numpy

我有一个 numpy 数组 [0, 1, 1, 2, 2, 0, 1, ...],它只包含数字 0-k。我想创建一个新数组,其中包含 n 个可能的 0-k 排列数组。一个 k=2 和 n=6 的小例子:

a = [0, 1, 0, 2]
permute(a)
result = [[0, 1, 0, 2]
          [0, 2, 0, 1]
          [1, 0, 1, 2]
          [2, 1, 2, 0]
          [1, 2, 1, 0]
          [2, 0, 2, 1]]

有没有人对如何实现这一目标有任何想法/解决方案?

最佳答案

您的 a 就是组合主义者所说的 multiset。 <强> sympy 图书馆有 various routines与他们一起工作。

>>> from sympy.utilities.iterables import multiset_permutations
>>> import numpy as np
>>> a = np.array([0, 1, 0, 2])
>>> for p in multiset_permutations(a):
...     p
...     
[0, 0, 1, 2]
[0, 0, 2, 1]
[0, 1, 0, 2]
[0, 1, 2, 0]
[0, 2, 0, 1]
[0, 2, 1, 0]
[1, 0, 0, 2]
[1, 0, 2, 0]
[1, 2, 0, 0]
[2, 0, 0, 1]
[2, 0, 1, 0]
[2, 1, 0, 0]

关于python - 获取 numpy 数组的所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41210142/

相关文章:

python - 重置 Pandas 数据框的列索引

python - 使用 Pyramid 认证

python - __reduce__ 和 __reduce_ex__ 有什么区别?

python - 如何更改numpy中矩阵对角线的值?

python - 如何将答案存储到 numpy 数组中并使用它来创建 Excel 工作表?

python - 将 `numpy` 数组的元素清零(按行)小于给定向量的值

python - 将函数广播到 3D 数组 Python

python - "Importerror: no module named zope.interface",但我已经在我的 Centos 7 上安装了

python - 以菱形填充的 Numpy 数组

python - 获取 werkzeug.routing.BuildError