我需要在表格样式矩阵中对 XYZ 坐标进行排序和数组,以导出为 .csv 文件。
在用户 Michael0x2a 的帮助下,我或多或少地做到了。我现在的问题是,如果我重复了 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([i[1] for i in array]))
height = len(x) + 1
width = 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: Printing"""
return '\n'.join(', '.join(str(i) for i in row) for row in matrix)
def main(array):
matrix = construct_initial_matrix(array)
matrix = add_edging(array, matrix)
matrix = add_z_coordinates(array, matrix)
print make_csv(matrix)
如果我运行下面的示例,它将返回
example = [[1, 1, 20], [1, 1, 11], [2, 3, 12.1], [2, 5, 13], [5,4,10], [3,6,15]]
main(example)
0, 1, 1, 3, 4, 5, 6
1, 0, 11, 0, 0, 0, 0
2, 0, 0, 12.1, 0, 13, 0
3, 0, 0, 0, 0, 0, 15
5, 0, 0, 0, 10, 0, 0
所以列标题是 y 值,行标题是 x 值。
对于第一组 [1,1,20] 它返回 1,1,0,因为第二组 [1,1,11] 具有相同的 x 和 y 值。
最终结果应该是:
0, 1, 1, 3, 4, 5, 6
1, 20, 11, 0, 0, 0, 0
2, 0, 0, 12.1, 0, 13, 0
3, 0, 0, 0, 0, 0, 15
5, 0, 0, 0, 10, 0, 0
我认为这与此功能有关:
x_to_pos = dict(zip(x, range(1, height)))
y_to_pos = dict(zip(y, range(1, width)))
谁能帮我解决这个问题?
非常感谢
弗朗西斯科