I need to sort and array of XYZ coordinates in a table style matrix to export as an .csv file.
With the help from user Michael0x2a I managed to do it more or less. My problem now is if I have repeated X and Y it will return 0 for Z.
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)
if I run the example below it will return
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
so column headers are the y values, row headers are the x values.
for the 1st set of [1,1,20] it returns 1,1,0 because of the second set [1,1,11] has the same x and y values.
the end result should be:
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
I think it has something to do with this function:
x_to_pos = dict(zip(x, range(1, height)))
y_to_pos = dict(zip(y, range(1, width)))
can anyone help me out with this?
thanks so much
Francisco