如何获取通过给定点的嵌套列表的对角线-Python



我有一个这样的2d列表:

thelist=[[0,0,0,0,0,0],
[1,0,0,0,0,0],
[0,1,0,0,0,0],
[0,0,1,0,0,0], # (3,2) is the 1 in this row
[0,0,0,1,0,0],
[0,0,0,0,1,0]]

我试图得到二维列表中穿过给定坐标的2条对角线。在上面的列表中,如果坐标是(3,2),那么这两个列表将是[1,1,1,1,1][0,0,1,0,0,0]

我见过可以得到所有对角线或特定对角线的解决方案,但我还没能在网上找到一个解决方案,可以得到穿过一点的对角线。以下是我尝试过的:

def find_diagonals(thelist,coor):
twodiag=[[],[]]
coor1=[coor[0]-min(coor),coor[1]-min(coor)]
coor2=[coor[0]-min(coor),coor[1]+min(coor)]
while True:
try: 
twodiag[0].append(thelist[coor1[0]][coor1[1]]) 
coor1[0]+=1
coor1[1]+=1
except IndexError:
break
while True:
try: 
twodiag[1].append(thelist[coor2[0]][coor2[1]]) 
coor2[0]+=1
coor2[1]-=1
except IndexError:
break
return twodiag

但是,它只正确返回一个对角线。如何修复此代码或以其他方式解决问题?如果有什么不清楚的地方,我很乐意在评论中回答。谢谢

使用numpy:的解决方案

import numpy as np
thelist=[[0,0,0,0,0,0],
[1,0,0,0,0,0],
[0,1,0,0,0,0],
[0,0,1,0,0,0], # (3,2) is the 1 in this row
[0,0,0,1,0,0],
[0,0,1,0,1,0]]
lst = matrix = np.array(thelist)
i, j = 3, 2 #position of element
major = np.diagonal(lst, offset=(j - i))
print(major)
minor = np.diagonal(np.rot90(lst), offset=-lst.shape[1] + (j + i) + 1)
print(minor)

输出:

[1 1 1 1 1]
[0 0 0 1 0 0]
width, height = len(thelist[0]), len(thelist)
size = max(width, height)
valid_x, valid_y = range(width), range(height)
pos = (3,2)
x, y = pos
diag1 = [thelist[i][i-x+y] for i in range(size) if i-x+y in valid_y]
diag2 = [thelist[i][x+y-i] for i in range(size) if x+y-i in valid_y]
print (diag1, diag2)
# [1, 1, 1, 1, 1] [0, 0, 0, 1, 0, 0]

最好的解决方案是简单的线性函数:

def find_diagonals(input_list, coordinates):
diagonals = [[], []]
row_coordinate, column_coordinates = coordinates
for row_number, row in enumerate(input_list):
diagonal_point = column_coordinates-row_coordinate+row_number
if 0 <= diagonal_point <= len(row):
diagonals[0].append(row[diagonal_point])
diagonal_point = column_coordinates+row_coordinate-row_number
if 0 <= diagonal_point <= len(row):
diagonals[1].append(row[diagonal_point])
return diagonals

您可以计算偏移量:

def get_diagonals(alist, coordinates):
# Diagonal 1
start = coordinates
while start[0] > 0 and start[1] > 0:
start = (start[0] - 1, start[1] - 1)
diag1 = []
index = start
while index[0] < len(alist) and index[1] < len(alist[0]):
diag1.append(alist[index[0]][index[1]])
index = (index[0] + 1, index[1] + 1)
# Diagonal 2
start = coordinates
while start[0] < len(alist) - 1 and start[1] > 0:
start = (start[0] + 1, start[1] - 1)
diag2 = []
index = start
while index[0] >= 0 and index[1] < len(alist[0]):
diag2.append(alist[index[0]][index[1]])
index = (index[0] - 1, index[1] + 1)
return diag1, diag2

thelist=[[0,0,0,0,0,0],
[1,0,0,0,0,0],
[0,1,0,0,0,0],
[0,0,1,0,0,0], # (3,2) is the 1 in this row
[0,2,0,1,0,0],
[3,0,0,0,1,0]]
coord = (3,2)
get_diagonals(thelist, coord)
> ([1, 1, 1, 1, 1], [3, 2, 1, 0, 0, 0])

该代码是直接的,并逐个计算矩阵中对角线上的位置。

编辑:修复了一个错误

最新更新