2017-03-06 127 views

回答

0

如何:

a = np.random.randint(0,20,(n,n)) 
a 
# array([[10, 4, 6, 12, 6], 
#  [ 5, 19, 1, 11, 5], 
#  [ 6, 10, 11, 1, 2], 
#  [ 5, 3, 0, 9, 1], 
#  [13, 13, 3, 15, 3]]) 
io = np.argsort(sum(np.ogrid[:n,:n]).ravel()) 
out = np.empty_like(a) 
out.ravel()[io] = np.sort(a.ravel()) 
out 
# array([[ 0, 1, 1, 3, 6], 
#  [ 1, 2, 3, 6, 10], 
#  [ 3, 5, 6, 9, 11], 
#  [ 4, 5, 10, 12, 13], 
#  [ 5, 11, 13, 15, 19]]) 

我們使用argsort在x和y指數的總和(使用生成ogrid)建立對角線順序。然後使用高級索引按順序放置a的排序元素。

+0

太棒了,謝謝 – saucypigeon