你可以打破這個問題分成以下幾個步驟:
- 獲取所有的獨特的X和Y座標
- 構建適當大小的表/矩陣
- 分配
x
和y
座標沿頂邊緣和左邊緣
- 迭代通過陣列,抓住
z
座標,並根據在矩陣其映射到正確的位置其x
和y
座標
- 輸出所得到的矩陣作爲csv文件。
我做如下假設:
- 如果給定
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(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()
你有什麼迄今所做? – badc0re
目前還不清楚規則是從輸入獲取輸出的是什麼?此外,你正在尋找什麼類型的輸出:另一種Python結構,打印到屏幕等?另外,您的輸入列表是否比所示的時間長,還是隻有這12個項目? – tom10
嗨,對不起,我應該提供更多信息。 輸出文件是一個在exel中打開的.csv文件。所以每行都是exel中的一行,每個「,」是exel中的一列。 數組是巨大的,上面的例子只是我雖然這將是解釋 – user2725701