【问题标题】:Getting all the combinations of a Numpy Array获取 Numpy 数组的所有组合
【发布时间】:2019-11-26 15:22:52
【问题描述】:

如果我有一个像 X=np.array([1,2,3,4,5]) 这样的 Numpy 数组 我想将这些数字的所有组合放入一个数组中。

我将如何获得一个数组,其中每一行都是 X 的组合,长度是多少组合?

【问题讨论】:

标签: python arrays numpy


【解决方案1】:

根据您的问题假设您实际上是在寻找排列:

from itertools import permutations

import numpy as np

x = np.array([1, 2, 3, 4, 5])

perm_array = np.asarray([p for p in permutations(x)])
print(perm_array.shape)
# prints(120, 5)

perm_array 的每一行都将包含您输入的排列。

注意排列的数量grows extremely quickly

【讨论】:

    【解决方案2】:

    在 itertools 中可用:

    from itertools import combinations
    X=np.array([1,2,3,4,5])
    X_combinations = {} # dictionary key r: combinations of rank r. 
    for r in range(len(X) + 1): 
      X_combinations[r] = list(combinations(X, r))
    
    from pprint import pprint
    pprint(X_combinations) 
    

    输出:

    {0: [()],
     1: [(1,), (2,), (3,), (4,), (5,)],
     2: [(1, 2),
         (1, 3),
         (1, 4),
         (1, 5),
         (2, 3),
         (2, 4),
         (2, 5),
         (3, 4),
         (3, 5),
         (4, 5)],
     3: [(1, 2, 3),
         (1, 2, 4),
         (1, 2, 5),
         (1, 3, 4),
         (1, 3, 5),
         (1, 4, 5),
         (2, 3, 4),
         (2, 3, 5),
         (2, 4, 5),
         (3, 4, 5)],
     4: [(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)],
     5: [(1, 2, 3, 4, 5)]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多