对于给定的二维正方形列表,说:
foo2d = [
[1, 1, 1, 1, 3],
[1, 3, 0, 3, 4],
[1, 1, 1, 1, 3],
[1, 3, 0, 2, 4],
[1, 3, 1, 3, 4]
]
我想要一个从(0,1)(foo2d[1][0]
)到与其对角点(2,3)(foo2d[3][2]
)的对角线列表。因此,在上面的玩具列表中,返回的列表应为:[1, 0, 1]
我尝试利用该线的斜率为1(或-1)这一事实,因此列表中的元素必须满足:
pointY - startY
abs(-----------------) == 1
pointX - startX
,且介于x最小值和x最大值之间。我没有代码实现,因为a)它破坏了所有内容,并且b)我在保存文件时计算机崩溃了,迫使我恢复为不包含该代码的git备份。
如果需要,我可以尝试为此行为编写一些伪代码。感谢您的任何想法,您可以给我解决这个问题!
答案 0 :(得分:1)
如果行的斜率只能是1或-1,则可以尝试以下操作:
def get_diagonal_points(matrix, start_x, start_y, end_x, end_y):
# make start_x <= end_x, if you don't need to check, remove this line
if start_x > end_x:
start_x, start_y, end_x, end_y = end_x, end_y, start_x, start_y
result = []
slope = (end_y - start_y) // (end_x - start_x)
for i, j in zip(range(start_x, end_x), range(start_y, end_y, slope)):
result.append(matrix[i][j])
result.append(matrix[end_x][end_y]) # add end point
return result
测试并输出:
foo2d = [
[1, 1, 1, 1, 3],
[1, 3, 0, 3, 4],
[1, 1, 1, 1, 3],
[1, 3, 0, 2, 4],
[1, 3, 1, 3, 4]
]
print(get_diagonal_points(foo2d, 0, 1, 2, 3))
# [1, 0, 1]
print(get_diagonal_points(foo2d, 0, 4, 3, 1))
# [3, 3, 1, 3]
print(get_diagonal_points(foo2d, 3, 1, 0, 4))
# [3, 3, 1, 3]