您可以将此问题分解为以下步骤:
- 获取所有唯一的 x 和 y 坐标
- 构建适当大小的表/矩阵
- 沿上边缘和左边缘分配
x
和坐标y
- 遍历数组,抓取坐标,根据其和坐标
z
映射到矩阵中正确的位置x
y
- 将生成的矩阵输出为 csv 文件。
我做出以下假设:
- 如果给定
x, y, z
坐标在数组中不存在,但在矩阵中有可用空间,则矩阵中的对应点将具有值“0”
- 数组中没有重复的坐标。
鉴于这些假设,下面的程序应该大致做我认为你想要的。
def find_x_and_y(array):
'''Step 1: Get unique x and y coordinates,
and the width and height of the matrix'''
x = sorted(list(set([i[0] for i in array])))
y = sorted(list(set([i[1] for i in array])))
width = len(x) + 1
height = len(y) + 1
return x, y, width, height
def construct_initial_matrix(array):
'''Step 2: Make the initial matrix (filled with zeros)'''
x, y, width, height = find_x_and_y(array)
matrix = []
for i in range(height):
matrix.append([0] * width)
return matrix
def add_edging(array, matrix):
'''Step 3: Add the x and y coordinates to the edges'''
x, y, width, height = find_x_and_y(array)
for coord, position in zip(x, range(1, height)):
matrix[position][0] = coord
for coord, position in zip(y, range(1, width)):
matrix[0][position] = coord
return matrix
def add_z_coordinates(array, matrix):
'''Step 4: Map the coordinates in the array to the position
in the matrix'''
x, y, width, height = find_x_and_y(array)
x_to_pos = dict(zip(x, range(1, height)))
y_to_pos = dict(zip(y, range(1, width)))
for x, y, z in array:
matrix[x_to_pos[x]][y_to_pos[y]] = z
return matrix
def make_csv(matrix):
'''Step 5: Pretty-printing'''
return '\n'.join(', '.join(str(i) for i in row) for row in matrix)
def main():
#example = [[1, 1, 10], [1, 2, 11], [2, 1, 12], [2, 2, 13]]
example = [[1000,250,12.2],[1000,500,10],[2000,250,15],[2000,500,13.5]]
matrix = construct_initial_matrix(example)
matrix = add_edging(example, matrix)
matrix = add_z_coordinates(example, matrix)
print make_csv(matrix)
main()