在Python中将XYZ坐标数组排序到表中

时间:2013-08-28 15:03:52

标签: python

我是python的新手,我无法弄清楚如何解决这个问题。 我有一个包含大量X,Y,Z坐标的数组,我需要创建一个输出文件将它们导入exel。

我导入了一个STL文件并从该文件中创建了一个2D数组

现在阵列是这样的:

example = [[X1,Y1,Z1],[X1,Y2,Z2],[X2,Y1,Z3],[X2,Y2,Z4]]

X和Y坐标重复很多,z总是不同。

我需要做的是使用此布局对它们进行排序,以将其保存为.csv文件:

example, Y1, Y2
X1, Z1, Z2
X2, Z3, Z4

所以将X坐标作为行,将Y列和Z放在相应的位置 有没有人可以帮我解决这个问题? 非常感谢提前。

1 个答案:

答案 0 :(得分:0)

您可以将此问题分解为以下步骤:

  1. 获取所有唯一的x和y坐标
  2. 构建适当大小的表/矩阵
  3. 沿顶部和左侧边缘分配xy坐标
  4. 遍历数组,抓取z坐标,并根据其xy坐标
  5. 将其映射到矩阵中的正确位置
  6. 将生成的矩阵输出为csv文件。
  7. 我做了以下假设:

    1. 如果数组中不存在给定的x, y, z坐标,但矩阵中有可用的空间,则矩阵中的相应点将具有值“0”
    2. 数组中没有重复的坐标。
    3. 鉴于这些假设,以下程序应该大致按照我的想法做。

      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()