获取numpy数组的所有置换

2024-04-29 18:52:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有人对如何实现这一目标有什么想法/解决方案吗?


Tags: numpy目标数字数组result解决方案例子permute
2条回答

你的a是组合学家称之为a多集的。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]

如果你的排列在内存中,你可以将它们存储在set中,因此只能得到可区分的排列。

from itertools import permutations

a = [0, 1, 0, 2]

perms = set()
for perm in permutations(a):
    perms.add(perm)

print(perms)

或者-正如John Coleman在一行中指出的那样:

perms = set(permutations(a))

相关问题 更多 >