简体   繁体   English

获取 numpy 数组的所有排列

[英]Get all permutations of a numpy array

I have a numpy array [0, 1, 1, 2, 2, 0, 1, ...] which only contains the numbers 0-k.我有一个 numpy 数组 [0, 1, 1, 2, 2, 0, 1, ...] 它只包含数字 0-k。 I would like to create a new array that contains the n possible arrays of permutations of 0-k.我想创建一个新数组,其中包含 n 个可能的 0-k 排列数组。 A small example with k=2 and n=6:一个 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]]

Does anyone have any ideas/solutions as to how one could achieve this?有没有人对如何实现这一目标有任何想法/解决方案?

Your a is what combinatorists call a multiset .你的a是组合学家所说的multiset The sympy library has various routines for working with them. sympy库有各种与它们一起工作的例程

>>> 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]

if your permutations fit in the memory, you could store them in a set and thus only get the distinguishable permutations.如果您的排列适合内存,您可以将它们存储在一个set ,从而只获得可区分的排列。

from itertools import permutations

a = [0, 1, 0, 2]

perms = set(permutations(a))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM