Python 用numpy生成n维中1和-1的所有组合?

Python 用numpy生成n维中1和-1的所有组合?,python,numpy,combinations,Python,Numpy,Combinations,我需要一种方法来生成一个numpy数组,该数组具有给定多个维度的[-1,1]的所有可能组合 例如,如果我有两个维度,我会得到: [1,1],[1,-1],-1,1],-1,-1]] 如果我有3个维度,我会得到: [1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],-1,1,1],-1,1,-1,1],-1,-1,1] 我试过这样的方法: import numpy as np def permgrid(n): inds = n

我需要一种方法来生成一个numpy数组,该数组具有给定多个维度的[-1,1]的所有可能组合

例如,如果我有两个维度,我会得到: [1,1],[1,-1],-1,1],-1,-1]]

如果我有3个维度,我会得到: [1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],-1,1,1],-1,1,-1,1],-1,-1,1]

我试过这样的方法:

import numpy as np                      
def permgrid(n):
    inds = np.indices((2,) * n)
    return inds.reshape(n, -1).T

但这只返回0和1的所有组合。

您可以使用itertools中的product函数

基本上,你可以得到所有重复2的组合

print (list(itertools.product([1,-1], repeat=2)))
itertools.product(*iterables[,repeat])

输入变量的笛卡尔积

大致相当于生成器表达式中的嵌套for循环


您可以在

中阅读更多信息。您可以使用itertools中的产品功能

基本上,你可以得到所有重复2的组合

print (list(itertools.product([1,-1], repeat=2)))
itertools.product(*iterables[,repeat])

输入变量的笛卡尔积

大致相当于生成器表达式中的嵌套for循环


您可以在

中阅读更多内容。您可能想看看
itertools
。它是一个用于生成排序序列等的包

import itertools as it

for element in it.combinations_with_replacement([1,-1],3):
  print element

您可能想看看
itertools
。它是一个用于生成排序序列等的包

import itertools as it

for element in it.combinations_with_replacement([1,-1],3):
  print element
这里有一个基于-

def broadcasting_typecast(n):
    return -2*((np.arange(2**n)[:,None] & (1 << np.arange(n-1,-1,-1))) != 0)+1
这里有一个基于-

def broadcasting_typecast(n):
    return -2*((np.arange(2**n)[:,None] & (1 << np.arange(n-1,-1,-1))) != 0)+1
要么替换

def permgrid(n):
    inds = np.indices((2,) * n)
    out = inds.reshape(n, -1).T
    return np.where(out==0, -np.ones_like(out), out)
或者用数学来做:

def permgrid(n):
    inds = np.indices((2,) * n)
    return inds.reshape(n, -1).T*2-1
要么替换

def permgrid(n):
    inds = np.indices((2,) * n)
    out = inds.reshape(n, -1).T
    return np.where(out==0, -np.ones_like(out), out)
或者用数学来做:

def permgrid(n):
    inds = np.indices((2,) * n)
    return inds.reshape(n, -1).T*2-1

您可以使用
np.ix
。优点:您可以轻松地将
-1,1
替换为任何您喜欢的内容(其他数字、其他数据类型、多于2等)

可选:

flat_out = np.reshape(out, (-1, n))

您可以使用
np.ix
。优点:您可以轻松地将
-1,1
替换为任何您喜欢的内容(其他数字、其他数据类型、多于2等)

可选:

flat_out = np.reshape(out, (-1, n))

只需将所有的零替换为-1即可。顺序重要吗?那就用-1替换所有的零。顺序重要吗?我认为这行不通;组合是无序的。不,它们不是。正如文档中提到的,它们可能因为是列表而有一个顺序,但并不是所有组合的顺序都会被返回,我认为OP希望这样。从文档中:
带替换的组合('ABCD',2)
-->
AA AB AC AD BB BC BD CC CD DD
<代码>它。使用替换([1,-1],3)的组合只会返回
[1,1,1],[1,1,-1],[1,-1],-1,-1]
;组合是无序的。不,它们不是。正如文档中提到的,它们可能因为是列表而有一个顺序,但并不是所有组合的顺序都会被返回,我认为OP希望这样。从文档中:
带替换的组合('ABCD',2)
-->
AA AB AC AD BB BC BD CC CD DD
<代码>它。使用替换([1,-1],3)的组合只会返回
[1,1,1],[1,1,-1],[1,-1],-1,-1]
。我认为您不需要像(out)这样的
-组合<代码>-1就可以了。我想你不需要这里的
-like(out)
<代码>-1即可。