Python 获取 numpy 数组的所有排列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41210142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:36:29  来源:igfitidea点击:

Get all permutations of a numpy array

pythonnumpy

提问by MBrown

I have a numpy array [0, 1, 1, 2, 2, 0, 1, ...] which only contains the numbers 0-k. I would like to create a new array that contains the n possible arrays of permutations of 0-k. A small example with k=2 and n=6:

我有一个 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]]

Does anyone have any ideas/solutions as to how one could achieve this?

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

回答by Bill Bell

Your ais what combinatorists call a multiset. The sympylibrary has various routinesfor working with them.

你的a是组合学家所说的multiset。该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]

回答by hiro protagonist

if your permutations fit in the memory, you could store them in a setand thus only get the distinguishable permutations.

如果您的排列适合内存,您可以将它们存储在 a 中set,从而只获得可区分的排列。

from itertools import permutations

a = [0, 1, 0, 2]

perms = set(permutations(a))