在Python中创建此numpy数组 [英] Creating this numpy array in Python
问题描述
我有以下numpy数组
I have the following numpy array
import numpy as np
a = np.array([1,2,6,8])
我想从a
创建另一个numpy数组,以使其包含a
的两个元素的所有不同可能和.然后很容易表明存在int(a.size*(a.size-1)/2)
个不同的和,它们由以下组成:
I want to create another numpy array from a
such that it contains all the different possible sums of TWO elements of a
. It's easy to show then that there are int(a.size*(a.size-1)/2)
different possible sums, composed from:
a[0] + a[1]
a[0] + a[2]
a[0] + a[3]
a[1] + a[2]
a[1] + a[3]
a[2] + a[3]
如何在不使用double for循环的情况下构造具有上述总和的numpy数组(我可以想到的唯一方法).对于上面的示例,输出应为[3,7,9,8,10,14]
How can I construct a numpy array with the above sums as elements without using a double for loop (the only way I can think of it). For the above example, the output should be [3,7,9,8,10,14]
MWE
eff = int(a.size*(a.size-1)/2)
c = np.empty((0, eff))
推荐答案
您可以使用triu_indices
:
i0,i1 = np.triu_indices(4,1)
a[i0]
# array([1, 1, 1, 2, 2, 6])
a[i1]
# array([2, 6, 8, 6, 8, 8])
a[i0]+a[i1]
# array([ 3, 7, 9, 8, 10, 14])
有关更多术语,我们需要构建自己的"nd_triu_idx".这是在5个列表中的3个词中执行此操作的方法:
For more terms we need to build our own "nd_triu_idx". Here is how to do it for 3 terms out of a list of 5:
n = 5
full = np.mgrid[:n,:n,:n]
nd_triu_idx = full[:,(np.diff(full,axis=0)>0).all(axis=0)]
nd_triu_idx
# array([[0, 0, 0, 0, 0, 0, 1, 1, 1, 2],
# [1, 1, 1, 2, 2, 3, 2, 2, 3, 3],
# [2, 3, 4, 3, 4, 4, 3, 4, 4, 4]])
要完全概括术语的数量,请使用类似的
To fully generalize the number of terms use something like
k = 4
full = np.mgrid[k*(slice(n),)]
等
这篇关于在Python中创建此numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!