简体   繁体   English

获取python 2d列表中2点之间对角线上的点列表

[英]get list of points on diagonal between 2 points in python 2d list

For a given square 2d list, say: 对于给定的二维二维列表,请说:

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]
]

I would like a list of the diagonals from (0, 1) ( foo2d[1][0] ) to the point diagonal from it, (2, 3) ( foo2d[3][2] ). 我想要一个从(0,1)( foo2d[1][0] )到对角线点(2,3)( foo2d[3][2] )的对角线foo2d[3][2] So in the toy list above, the returned list should be: [1, 0, 1] 因此,在上面的玩具列表中,返回的列表应为: [1, 0, 1]

I have tried taking advantage of the fact that the slope of that line is 1 (or -1), so an element on the list would have to satisfy: 我尝试利用该线的斜率为1(或-1)这一事实,因此列表中的一个元素必须满足:

     pointY - startY
abs(-----------------) == 1
     pointX - startX

and be between the x minimum and x maximum. 并且介于x最小值和x最大值之间。 I don't have the code implementation because a) it broke everything and b) my computer crashed just as I was saving the file, forcing me to revert to a git backup that did not contain that code. 我没有代码实现,因为a)它破坏了所有内容,并且b)我在保存文件时计算机崩溃了,迫使我恢复为不包含该代码的git备份。

If you need it, I can try to write some pseudo code for this behavior. 如果需要,我可以尝试为此行为编写一些伪代码。 Thanks for any thoughts you can give me with this issue! 感谢您的任何想法,您可以给我这个问题!

If the slop of line only can be 1 or -1, you can try this: 如果行的斜率只能是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

test and output: 测试输出:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM