2013-08-28 64 views
-3

我很新的蟒蛇,我無法弄清楚如何來解決這個問題。 我有一個有很多X,Y,Z座標的數組,我需要創建一個輸出文件將它們導入exel。排序XYZ座標數組到表中的Python

我導入的STL文件,並把創建從該文件中的二維數組

眼下陣列是這樣的:

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 這可以幫助我嗎? 非常感謝。

+0

你有什麼迄今所做? – badc0re

+0

目前還不清楚規則是從輸入獲取輸出的是什麼?此外,你正在尋找什麼類型的輸出:另一種Python結構,打印到屏幕等?另外,您的輸入列表是否比所示的時間長,還是隻有這12個項目? – tom10

+0

嗨,對不起,我應該提供更多信息。 輸出文件是一個在exel中打開的.csv文件。所以每行都是exel中的一行,每個「,」是exel中的一列。 數組是巨大的,上面的例子只是我雖然這將是解釋 – user2725701

回答

0

你可以打破這個問題分成以下幾個步驟:

  1. 獲取所有的獨特的X和Y座標
  2. 構建適當大小的表/矩陣
  3. 分配xy座標沿頂邊緣和左邊緣
  4. 迭代通過陣列,抓住z座標,並根據在矩陣其映射到正確的位置其xy座標
  5. 輸出所得到的矩陣作爲csv文件。

我做如下假設:

  1. 如果給定x, y, z座標陣列中不存在,但在基質中爲它提供一個空間,在矩陣中的對應點會具有值「0」
  2. 數組中沒有重複的座標。

鑑於這些假設,下面的程序應該大致做我認爲你想要的。

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

UAU的最佳方式,它看起來很多更復雜的話,我期待:)我會揣摩出來,我相信我會的方式對你的帖子有幾小時的跟蹤和錯誤,但我想我可以理解它。非常感謝你的回覆 – user2725701

+0

我不能讓它工作,一直得到同樣的錯誤:range()整數結束參數預期,得到浮動。 無法弄清楚什麼是問題。 – user2725701

+0

@ user2725701座標是浮點數嗎?我認爲他們是整數。如果它們是浮點數,那麼你可以編輯你的問題,在數組中包含大約10個實際座標的snippit,以及如果數組很短,那麼期望的輸出? – Michael0x2a