二维数组的所有元素的所有组合 [英] All combinations of all elements of a 2D array

查看:19
本文介绍了二维数组的所有元素的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有矩阵A

A = [[0,0,1,-1] 
     [0,0,1,-1]
     [0,0,1,-1]
     [0,0,1,-1]]
我想要这些元素的所有可能的组合。这意味着行也可以在它们和列之间更改。在这种情况下,我预计有4^4 = 256种可能性。我已尝试:

combs = np.array(list(itertools.product(*A)))

它确实创建了我,我希望输出(256,4)矩阵,但是所有行都是相等的。这意味着我得到向量[0,0,1,-1]256次。

举个例子:

output = [[0,0,0,0]
          [0,0,0,1]
          [0,0,1,1]
          [0,1,1,1]
          [1,1,1,1]
          [-1,1,1,-1]
          [-1,-1,-1,-1]
             ....
          [0,-1,0,-1]

另一个示例,如果

A = [[1,2,3] 
     [4,5,6]
     [7,8,9]]

输出应该是矩阵可以形成的所有可能的数组组合

Combs =[[1,1,1] 
        [1,1,2]
        [1,1,3]
        [1,1,...9]
        [2,1,1]
        [2,2,1]
        [1,2,1]
另一个示例是: 我有矢量图层

layers = [1,2,3,4,5]

然后我有向量角

angle = [0,90,45,-45]

每层可以有一个角度,所以我创建了一个矩阵A

A = [[0,90,45,-45]
     [0,90,45,-45]
     [0,90,45,-45]
     [0,90,45,-45]
     [0,90,45,-45]]

很好,但是现在我想知道各层可以有的所有可能的组合。例如,层1的角度可以是0º,层2的角度可以是90º,层3的角度可以是0º,层4的角度可以是45º,层5的角度可以是0º。这将创建数组

Comb = [0,90,0,45,0]

所以所有的组合都在一个矩阵中

Comb = [[0,0,0,0,0]
        [0,0,0,0,90]
        [0,0,0,90,90]
        [0,0,90,90,90] 
        [0,90,90,90,90] 
        [90,90,90,90,90] 
             ...
        [0,45,45,45,45]
        [0,45,90,-45,90]]

如何将此过程推广到更大的矩阵。

我做错了什么吗?

谢谢!

推荐答案

可以将np.arraylist(Iterable)结合使用,尤其是在Iterableitertools.product(*A)的情况下。但是,由于您知道输出的数组形状,因此可以对此进行优化。

执行product的方式有很多,所以我只列出我的列表:

笛卡尔乘积方法

import itertools
import numpy as np

def numpy_product_itertools(arr):
    return np.array(list(itertools.product(*arr)))

def numpy_product_fromiter(arr):
    dt = np.dtype([('', np.intp)]*len(arr)) #or np.dtype(','.join('i'*len(arr)))
    indices = np.fromiter(itertools.product(*arr), dt)
    return indices.view(np.intp).reshape(-1, len(arr))

def numpy_product_meshgrid(arr):
    return np.stack(np.meshgrid(*arr), axis=-1).reshape(-1, len(arr))

def numpy_product_broadcast(arr): #a little bit different type of output
    items = [np.array(item) for item in arr]
    idx = np.where(np.eye(len(arr)), Ellipsis, None)
    out = [x[tuple(i)] for x,i in zip(items, idx)]
    return list(np.broadcast(*out))

用法示例

A = [[1,2,3], [4,5], [7]]
numpy_product_itertools(A)
numpy_product_fromiter(A)
numpy_product_meshgrid(A)
numpy_product_broadcast(A)

绩效对比

import benchit
benchit.setparams(rep=1)
%matplotlib inline
sizes = [3,4,5,6,7]
N = sizes[-1]
arr = [np.arange(0,100,10).tolist()] * N
fns = [numpy_product_itertools, numpy_product_fromiter, numpy_product_meshgrid, numpy_product_broadcast]
in_ = {s: (arr[:s],) for s in sizes}
t = benchit.timings(fns, in_, multivar=True, input_name='Cartesian product of N arrays of length=10')
t.plot(logx=False, figsize=(12, 6), fontsize=14)

请注意,numba击败了这些算法中的大多数,尽管它不包括在内。

这篇关于二维数组的所有元素的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆