在不使用numpy的情况下得到nxn矩阵的所有对角元素,
这与Get diagonal without using numpy in Python
请不要标为副本。
这是我使用两次迭代的代码片段,它将打印从(0,0)到(n,n)的所有对角线元素。有人能帮我改进迭代过程或任何递归的方法吗。
#!/usr/bin/python
matrix = [[1,2,3,4],
[2,3,4,5],
[3,4,5,6],
[4,5,6,7]]
def get_matrix_diagonal(m):
col = len(m)
result = list()
row = 0
for c in range(col):
position = list()
position.append([row,c])
if c > 0:
i = c
while i > 0:
x = i - 1
y = c - i + 1
position.append([y,x])
i -= 1
result.append(position)
row = row + 1
cc = c
for i in range(row,col):
position = list()
y = i
x = c
position.append([y,x])
j = x - y
while j > 0:
y = c - j + 1
x = cc - y + 1
position.append([y,x])
j -= 1
cc += 1
result.append(position)
return result
for ls in get_matrix_diagonal(matrix):
for co in ls:
x,y = co[0],co[1],
print matrix[x][y],
print
输出:
1
2 2
3 3 3
4 4 4 4
5 5 5
6 6
7
最佳答案
>>> matrix = [[1,2,3,4],
... [2,3,4,5],
... [3,4,5,6],
... [4,5,6,7]]
>>> N = 4
>>> [[matrix[y-x][x] for x in range(N) if 0<=y-x<N] for y in range(2*N-1)]
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5], [6, 6], [7]]
关于python - NXN矩阵的所有对角元素,而在python中不使用numpy,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20696924/