擅长:python、mysql、java
<p>下面的函数基于<code>indices</code>比较,基于每个对角线都有一个索引关系的事实,例如在主对角线<code>i==j</code>,依此类推。。。在</p>
<p>对于非平方数组有效。在</p>
<pre><code>def flatten_diagonally(x, diags=None):
diags = np.array(diags)
if x.shape[1] > x.shape[0]:
diags += x.shape[1]-x.shape[0]
n = max(x.shape)
ndiags = 2*n-1
i,j = np.indices(x.shape)
d = np.array([])
for ndi in range(ndiags):
if diags != None:
if not ndi in diags:
continue
d = np.concatenate((d,x[i==j+(n-1)-ndi]))
return d
</code></pre>
<p>示例:</p>
^{pr2}$
<p>对于非平方数组:</p>
<pre><code>A=np.array([[1,2,3],
[7,8,9]])
print flatten_diagonally(A, diags=(1,2))
#[ 1. 8. 2. 9.]
</code></pre>