Sorting array of XYZ coordinates into table in Python -
i'm new python , can't figure out how solve problem. have array lots of x,y,z coordinates , need create output file import them exel.
i imported stl file , put created 2d array file
right array this:
example = [[x1,y1,z1],[x1,y2,z2],[x2,y1,z3],[x2,y2,z4]]
the x , y coordinates repeat alot , z different.
what need sort them layout save .csv file:
example, y1, y2 x1, z1, z2 x2, z3, z4
so put x coordinates rows, y columns , z in corresponding place can me out this? in advance.
you can break problem following steps:
- get unique x , y coordinates
- construct table/matrix of appropriate size
- assign
x
,y
coordinates along top , left edges - iterate through array, grab
z
coordinate, , map correct location in matrix accordingx
,y
coordinates - output resulting matrix csv file.
i'm making following assumptions:
- if given
x, y, z
coordinate not exist in array, has space available within matrix, corresponding spot in matrix have value "0" - there no duplicate coordinates within array.
given these assumptions, following program should think want.
def find_x_and_y(array): '''step 1: unique x , y coordinates, , width , height of matrix''' x = sorted(list(set([i[0] in array]))) y = sorted(list(set([i[1] in array]))) width = len(x) + 1 height = len(y) + 1 return x, y, width, height def construct_initial_matrix(array): '''step 2: make initial matrix (filled zeros)''' x, y, width, height = find_x_and_y(array) matrix = [] in range(height): matrix.append([0] * width) return matrix def add_edging(array, matrix): '''step 3: add x , y coordinates edges''' x, y, width, height = find_x_and_y(array) coord, position in zip(x, range(1, height)): matrix[position][0] = coord coord, position in zip(y, range(1, width)): matrix[0][position] = coord return matrix def add_z_coordinates(array, matrix): '''step 4: map coordinates in array position in 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))) 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) in row) 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()
Comments
Post a Comment