Arrays 如何根据对数公式连接数组

Arrays 如何根据对数公式连接数组,arrays,python-3.x,numpy,Arrays,Python 3.x,Numpy,我有一些数组。现在,我想根据这个公式连接这些数组(n*(n-1)/2)。比如说,我有3个数组,我可以使用下面的函数连接 def concat(): arrays = get_arrays() # this function returns some arrays array1 = array[0].reshape(-1, 1) array2 = array[1].reshape(-1, 1) array3 = array[2].reshape(-1, 1) concate_

我有一些数组。现在,我想根据这个公式连接这些数组(
n*(n-1)/2
)。比如说,我有3个数组,我可以使用下面的函数连接

def concat():
  arrays = get_arrays() # this function returns some arrays
  array1 = array[0].reshape(-1, 1)
  array2 = array[1].reshape(-1, 1)
  array3 = array[2].reshape(-1, 1)

  concate_1_2 = np.concatenate([array1, array2], axis=1)
  concate_1_3 = np.concatenate([array1, array3], axis=1)
  concate_2_3 = np.concatenate([array2, array3], axis=1)
我不需要
concate_1_1、concate_2_2等
。同样,我不想要
concate_2_1和concate_3_1
,因为我已经有了
concate_1_2和concate_1_3
。因为我有3个数组,所以根据公式,我得到了
3*(3-1)/2=3
串联

现在,问题是,我可以有不同数量的数组(不仅仅是固定的3或4)。我可以有10或20个阵列。那么我如何动态地解决这个问题(不是手动编写,
concate\u 1\u 2
concate\u 1\u 3
,等等)

一个可能的解决方案

import numpy as np;

def concat(array):
  (nR, nC) = array.shape; #Number of rows and columns
  concatenationContainer = np.zeros((int(nR*(nR-1)/2), 2*nC)); #add concatenate_1_2, concatenate_1_3, etc..
  counter = 0; #Index of the concatenationContainer array

  for row in range(nR): #For each row
    arrayRow = array[row]; #Obtain the next row
    for nextRow in range(row + 1, nR): #For each row that still wasn't concatenated with arrayRow
      concatenationContainer[counter] = np.append(arrayRow, array[nextRow]); #Concatenate
      counter+=1; #Update counter

  return concatenationContainer;

if __name__ == '__main__':
  example = np.zeros((4,4));
  example[1] = 1;
  example[2] = 2;
  example[3] = 3;  
  print(example);
  print(concat(example));
例如,此运行代码采用以下矩阵:

[[0. 0. 0. 0.]
 [1. 1. 1. 1.]
 [2. 2. 2. 2.]
 [3. 3. 3. 3.]]
返回

[[0. 0. 0. 0. 1. 1. 1. 1.]
 [0. 0. 0. 0. 2. 2. 2. 2.]
 [0. 0. 0. 0. 3. 3. 3. 3.]
 [1. 1. 1. 1. 2. 2. 2. 2.]
 [1. 1. 1. 1. 3. 3. 3. 3.]
 [2. 2. 2. 2. 3. 3. 3. 3.]]

您可以使用
itertools
组合
。下面给出了一个简单的例子,如果您想对2个列表进行组合

代码

输出

[('a', 'b'), ('a', 'c'), ('b', 'c')]

有关更多信息,请参阅。

非常感谢。运行代码后,我会通知您,并会通知您。好的,请再次检查代码。我在更新计数器时遇到了错误的缩进(已修复),并删除了.Reformate(-1,1)方法,因为它们不是必需的。@Servetti谢谢。代码按照公式工作,但我需要使用重塑(-1,-1)轴=1按列添加它们。否则,我以后的代码将无法工作!比如,我想得到
[[0,1],[0,1],[0,1],[0,1]
而不是得到它们
[0.0.0.0.1.1.1.]
[('a', 'b'), ('a', 'c'), ('b', 'c')]