获取python 2D列表中两个点之间对角线上的点列表,可以通过以下步骤实现:
下面是一个示例代码,演示如何实现上述步骤:
def get_diagonal_points(matrix, point1, point2):
x1, y1 = point1
x2, y2 = point2
dx = x2 - x1
dy = y2 - y1
# 确定行和列的增量方向
if dx >= 0 and dy >= 0:
row_increment = 1
col_increment = 1
elif dx >= 0 and dy < 0:
row_increment = 1
col_increment = -1
elif dx < 0 and dy >= 0:
row_increment = -1
col_increment = 1
else:
row_increment = -1
col_increment = -1
# 生成对角线上的点列表
diagonal_points = []
row = x1
col = y1
while row != x2 and col != y2:
diagonal_points.append(matrix[row][col])
row += row_increment
col += col_increment
return diagonal_points
使用示例:
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
point1 = (0, 0)
point2 = (2, 2)
diagonal_points = get_diagonal_points(matrix, point1, point2)
print(diagonal_points)
输出结果为:[1, 5, 9]
以上代码是一个简单的实现示例,可以根据实际需求进行修改和优化。
领取专属 10元无门槛券
手把手带您无忧上云