Numpy:如何生成特定数组(迭代器更好)

Numpy:如何生成特定数组(迭代器更好),numpy,combinatorics,Numpy,Combinatorics,我需要一个数组或迭代器来循环,具有以下特征: 1°我有一组$d$向量,大小为$n$(随机,排序),比如x[0],…,x[d-1] 2°我希望每个迭代值都是一个向量od size$d$,包含上述向量的所有潜在值组合。这意味着: y[0] : [x[0,0], x[1,0],....,x[d-1,0]] y[1] : [x[0,1], x[1,0],....,x[d-1,0]] y[2] : [x[0,0], x[1,1],....,x[d-1,0]] ... y

我需要一个数组或迭代器来循环,具有以下特征:

1°我有一组$d$向量,大小为$n$(随机,排序),比如x[0],…,x[d-1]

2°我希望每个迭代值都是一个向量od size$d$,包含上述向量的所有潜在值组合。这意味着:

y[0]       : [x[0,0], x[1,0],....,x[d-1,0]]
y[1]       : [x[0,1], x[1,0],....,x[d-1,0]]
y[2]       : [x[0,0], x[1,1],....,x[d-1,0]]
...
y[-1]      : [x[0,n-1], x[1,n-1],...., x[d-1,n-1]]
如何生成这个数组或迭代器

例如,对于d=3和n=3,这将产生以下向量:

y[0]       : [x[0,0], x[1,0], x[2,0]]
y[1]       : [x[0,1], x[1,0], x[2,0]]
y[2]       : [x[0,2], x[1,0], x[2,0]]

y[3]       : [x[0,0], x[1,1], x[2,0]]
y[4]       : [x[0,1], x[1,1], x[2,0]]
y[5]       : [x[0,2], x[1,1], x[2,0]]

y[6]       : [x[0,0], x[1,2], x[2,0]]
y[7]       : [x[0,1], x[1,2], x[2,0]]
y[8]       : [x[0,2], x[1,2], x[2,0]]

y[9]       : [x[0,0], x[1,0], x[2,1]]
y[10]      : [x[0,1], x[1,0], x[2,1]]
y[11]      : [x[0,2], x[1,0], x[2,1]]

y[12]      : [x[0,0], x[1,1], x[2,1]]
y[13]      : [x[0,1], x[1,1], x[2,1]]
y[14]      : [x[0,2], x[1,1], x[2,1]]

y[15]      : [x[0,0], x[1,2], x[2,1]]
y[16]      : [x[0,1], x[1,2], x[2,1]]
y[17]      : [x[0,2], x[1,2], x[2,1]]

y[18]      : [x[0,0], x[1,0], x[2,2]]
y[19]      : [x[0,1], x[1,0], x[2,2]]
y[20]      : [x[0,2], x[1,0], x[2,2]]

y[21]      : [x[0,0], x[1,1], x[2,2]]
y[22]      : [x[0,1], x[1,1], x[2,2]]
y[23]      : [x[0,2], x[1,1], x[2,2]]

y[24]      : [x[0,0], x[1,2], x[2,2]]
y[25]      : [x[0,1], x[1,2], x[2,2]]
y[26]      : [x[0,2], x[1,2], x[2,2]]
我甚至不知道应该有多少取决于(n,d)


你有什么想法吗?

可能有更简洁的方法来做这件事,但我认为这就是要求的

import numpy as np

def rows( d, n ):
    """ Generates row indices. """
    arr = np.zeros( shape = d, dtype = np.int )

    def inc_row( arr ):
        for ix in range(0, len(arr)):
            arr[ ix ] += 1
            if arr[ ix ] < n:
                return arr   # If arr[ix] doesn't roll over return arr
            arr[ ix ] = 0      # Reset arr[ix] to zero if it rolls over
        return None   # Return None once all indices reset to zero. 

    while not arr is None:
        yield arr
        arr = inc_row( arr )

def permutations( base, d, n ):
    """ Generate the required combinations of values from base. """
    cols = np.arange( d )
    res = []
    for row in rows( d, n ):
        res.append( base[ row, cols ] )
    return np.array(res)

d = 3
n = 2

base = np.fromfunction( lambda x,y : x+y/10, shape = (n,d))
# For testing 'base' array values indicate location r.c

print(base)
# [[0.  0.1 0.2]
#  [1.  1.1 1.2]]

print(permutations( base, d, n ))
# [[0.  0.1 0.2]
#  [1.  0.1 0.2]
#  [0.  1.1 0.2]
#  [1.  1.1 0.2]
#  [0.  0.1 1.2]
#  [1.  0.1 1.2]
#  [0.  1.1 1.2]
#  [1.  1.1 1.2]]
将numpy导入为np
def行(d,n):
“”“生成行索引。”“”
arr=np.zero(shape=d,dtype=np.int)
def inc_行(arr):
对于范围(0,len(arr))内的ix:
arr[ix]+=1
如果arr[ix]