如果你想要一个从corner1到corner2的对角线并以形式定义角落
(0,0,0,…,0),(0,0,0,….,1),…,(1,1,1,…,1)
其中0表示“此维度为0”,1表示“此维度为-1 /结束”
然后,这将返回从corner1到corner2获得的值,假设数组在每个维度中具有相同的大小.
import numpy
def diagonal(arr,corner1,corner2):
arr=numpy.array(arr)
#Change values to fit array
corner1Copy=(len(arr)-1)*numpy.array(corner1)
corner2Copy=(len(arr)-1)*numpy.array(corner2)
#create return array by running from corner1 to corner2 and returning the values
return [arr[tuple((i*corner2Copy+(len(arr)-i-1)*corner1Copy)/(len(arr)-1))] for i in range(len(arr))]
这里有两个小的测试案例,但我建议创建更多,以防我错过了一些东西:
arr=[[[i+j+k for i in range(5)]for j in range(5)] for k in range(5)]
corner1=[0,0,0]
corner2=[1,1,1]
#returns arr[0,0,0],arr[1,1,1],....,arr[-1,-1,-1]
print(diagonal(arr,corner1,corner2))
print([arr[i][i][i] for i in range(len(arr))])
arr2=[[i+j for i in range(5)]for j in range(5)]
corner12=[0,1]
corner22=[1,1]
#return arr[0,-1],arr[1,-1],....,arr[-1,-1]
print(diagonal(arr2,corner12,corner22))
print([arr2[i][-1] for i in range(len(arr2))])