鉴于3维中的标准基矢(e_1,e_2,e_3)
并且允许(e_1,e_2,e_3)
的元素被限制,比如(0,1,2,3,4)
是否有一种简单的pythonic方法来创建所有的笛卡尔积这个向量空间中的向量?
例如,给定[1,0,0],[0,1,0]和[0,0,1],我想获得所有线性组合的列表(其中a_i&#39 ; s被限制在[0,0,0]和[4,4,4]之间的这些向量的0到4之间的自然。
我可以自己编程,但在遇到麻烦之前,我想我会问是否有一种简单的pythonic方法,可能是numpy或类似的东西。
答案 0 :(得分:1)
对于自然数字空间的特定情况,您需要np.indices
:
>>> np.indices((4, 4)).reshape(2,-1).T
array([[0, 0],
[0, 1],
[0, 2],
[0, 3],
[1, 0],
[1, 1],
[1, 2],
[1, 3],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[3, 0],
[3, 1],
[3, 2],
[3, 3]])
(numpy实际上在网格中输出这些,但你想要一个点的一个列表,因此.reshape
)
否则,您所描述的不是一个powerset而是一个笛卡尔产品
itertools.product(range(4), repeat=3)
答案 1 :(得分:0)
编辑:这个答案有效,但我认为Eric更好,因为它更容易推广。
为了帮助可能偶然发现这个问题的其他人。这是一个非常简单的方法来做上述问题。它使用np.where来查找满足特定标准的矩阵的所有索引。在这里,我们的标准只是所有矩阵都满足的。这相当于上面的问题。这仅适用于上述示例,但要将其概括为N维并不太难。
import numpy as np
dim=3
gran=5
def vec_powerset(dim, gran):
#returns a list of all the vectors for a three dimensional vector space
#where the elements of the vectors are the naturals up to gran
size=tuple([gran]*dim)
a=np.zeros(size)
return [[np.where(a>(-np.inf))[0][x],np.where(a>(-np.inf))[1][x],
np.where(a>(-np.inf))[2][x]] for x in
range(len(np.where(a>(-np.inf))[0]))]
print vec_powerset(dim,gran)
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 0, 4], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 0], [0, 2, 1], [0, 2, 2], [0, 2, 3], [0, 2, 4], [0, 3, 0], [0, 3, 1], [0, 3, 2], [0, 3, 3], [0, 3, 4], [0, 4, 0], [0, 4, 1], [0, 4, 2], [0, 4, 3], [0, 4, 4], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 0, 3], [1, 0, 4], [1, 1, 0], [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [1, 2, 0], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, 2, 4], [1, 3, 0], [1, 3, 1], [1, 3, 2], [1, 3, 3], [1, 3, 4], [1, 4, 0], [1, 4, 1], [1, 4, 2], [1, 4, 3], [1, 4, 4], [2, 0, 0], [2, 0, 1], [2, 0, 2], [2, 0, 3], [2, 0, 4], [2, 1, 0], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [2, 2, 0], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 2, 4], [2, 3, 0], [2, 3, 1], [2, 3, 2], [2, 3, 3], [2, 3, 4], [2, 4, 0], [2, 4, 1], [2, 4, 2], [2, 4, 3], [2, 4, 4], [3, 0, 0], [3, 0, 1], [3, 0, 2], [3, 0, 3], [3, 0, 4], [3, 1, 0], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4], [3, 2, 0], [3, 2, 1], [3, 2, 2], [3, 2, 3], [3, 2, 4], [3, 3, 0], [3, 3, 1], [3, 3, 2], [3, 3, 3], [3, 3, 4], [3, 4, 0], [3, 4, 1], [3, 4, 2], [3, 4, 3], [3, 4, 4], [4, 0, 0], [4, 0, 1], [4, 0, 2], [4, 0, 3], [4, 0, 4], [4, 1, 0], [4, 1, 1], [4, 1, 2], [4, 1, 3], [4, 1, 4], [4, 2, 0], [4, 2, 1], [4, 2, 2], [4, 2, 3], [4, 2, 4], [4, 3, 0], [4, 3, 1], [4, 3, 2], [4, 3, 3], [4, 3, 4], [4, 4, 0], [4, 4, 1], [4, 4, 2], [4, 4, 3], [4, 4, 4]]