【问题标题】:How to get all possible shuffle combinations using numpy如何使用 numpy 获得所有可能的随机播放组合
【发布时间】:2020-05-01 16:20:59
【问题描述】:

我有一个长度为 N 的 NumPy 数组,其中包含 XN-X 零。我想为我的数组生成所有可能的随机播放组合。

比如N是5,X是2,我需要下面的组合,

[0, 0, 1, 1, 0]
[1, 1, 0, 0, 0]
[0, 0, 0, 1, 1]
[0, 0, 1, 0, 1]
[1, 0, 0, 1, 0]
[0, 1, 1, 0, 0]
[0, 1, 0, 1, 0]
[1, 0, 1, 0, 0]
[0, 1, 0, 0, 1]
[1, 0, 0, 0, 1]

在 numpy 中是否有任何直接的方法可以做到这一点?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    组合在 Python 标准库中实现,位于 itertools。它从N 列表中选择X 元素,因此您可以让它选择索引并将其设置为1

    import numpy as np
    from itertools import combinations
    
    N = 5
    X = 2
    
    for combination in combinations(range(N), X):
        arr = np.zeros(N)
        arr[list(combination)] = 1
        print(arr)
    

    输出:

    [1. 1. 0. 0. 0.]
    [1. 0. 1. 0. 0.]
    [1. 0. 0. 1. 0.]
    [1. 0. 0. 0. 1.]
    [0. 1. 1. 0. 0.]
    [0. 1. 0. 1. 0.]
    [0. 1. 0. 0. 1.]
    [0. 0. 1. 1. 0.]
    [0. 0. 1. 0. 1.]
    [0. 0. 0. 1. 1.]
    

    【讨论】:

      【解决方案2】:

      这是一个带有itertools.combinations 的矢量化文件-

      from itertools import combinations
      
      def combs(N, X):
          idx = np.array(list(combinations(range(N), X)))
          n = len(idx)
          out = np.zeros((n,N), dtype=int)
          out[np.arange(n)[:,None],idx] = 1
          return out
      

      示例运行 -

      In [57]: combs(N=5, X=2)
      Out[57]: 
      array([[1, 1, 0, 0, 0],
             [1, 0, 1, 0, 0],
             [1, 0, 0, 1, 0],
             [1, 0, 0, 0, 1],
             [0, 1, 1, 0, 0],
             [0, 1, 0, 1, 0],
             [0, 1, 0, 0, 1],
             [0, 0, 1, 1, 0],
             [0, 0, 1, 0, 1],
             [0, 0, 0, 1, 1]])
      
      In [58]: combs(N=5, X=3)
      Out[58]: 
      array([[1, 1, 1, 0, 0],
             [1, 1, 0, 1, 0],
             [1, 1, 0, 0, 1],
             [1, 0, 1, 1, 0],
             [1, 0, 1, 0, 1],
             [1, 0, 0, 1, 1],
             [0, 1, 1, 1, 0],
             [0, 1, 1, 0, 1],
             [0, 1, 0, 1, 1],
             [0, 0, 1, 1, 1]])
      
      In [59]: combs(N=5, X=4)
      Out[59]: 
      array([[1, 1, 1, 1, 0],
             [1, 1, 1, 0, 1],
             [1, 1, 0, 1, 1],
             [1, 0, 1, 1, 1],
             [0, 1, 1, 1, 1]])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-21
        • 2014-04-21
        • 2012-11-25
        • 1970-01-01
        • 2019-10-25
        • 2013-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多