【发布时间】:2013-12-20 05:32:20
【问题描述】:
尝试在不使用numpy的情况下获取NXN矩阵的所有对角元素,
这与Get diagonal without using numpy in Python不同
请不要标记为重复。
这是我的 sn-p 使用两次迭代,它将打印从 (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
【问题讨论】:
-
我没有投票赞成关闭,但实际上我认为最好在 codereview 上问这个问题
-
好的,下次会这样做,谢谢。