2015-09-01 26 views
3

作爲輸入,我收到由表示多邊形和多面幾何的x和y座標組成的列表的兩種列表。事實上,輸入在GeoJson standardPython - 在一個函數中展平兩種不同類型的列表

list1表示表示一個簡單的多邊形幾何形狀的座標和list2表示MULTIPOLYGON幾何:

list1 = [[[0 , 0], [0, 1], [0 ,2]]] 

list2 = [[[[0, 0] , [0, 1], [0, 2]], [[1, 0], [1, 1], [1 ,2]]]] 

組合區幾何形狀(list2)由列表的列表更深一層表示比簡單的多邊形幾何(list1)。

我想拉平這些名單,以便讓那些輸出:

if input is list1 type : list1_out = [[0, 0, 0, 1, 0, 2]] 

    if input is list2 type : list2_out = [[0, 0, 0, 1, 0, 2], [1, 0, 1, 1, 1, 2]] 

我使用下面的代碼,通常被用來壓平列表,其中input可以是兩種類型的列表:

[coords for polygon in input for coords in polygon] 

通過以上這種代碼,輸出爲list1是正確的,但的list2輸出如下:

[[[0, 0] ,[0, 1], [0, 2]], [1, 0], [1, 1], [1, 2]]] 

是否有一個函數可以將這兩種類型的列表深度扁平化以獲得預期的輸出結果?

編輯:性能真正的問題在這裏的列表是真正的大

編輯2:我可以if語句使用每種類型的列表

+0

所以,你要只扁平化最內部的名單?此外,它是否需要自動檢測它是什麼樣的列表? –

+0

是的,這是一個很好的總結! –

+0

'list2'的結果不應該是'[[[0,0,0,1,0,2],[1,0,1,1,1,2]]]'? (又一個級別的'[]') –

回答

1

嘗試;

list1

[sum(x, []) for x in list1] 

list2

[sum(x, []) for a in list2 for x in a] 

演示

>>> list1 = [[[0 , 0], [0, 1], [0 ,2]]] 
>>> list2 = [[[[0, 0] , [0, 1], [0, 2]], [[1, 0], [1, 1], [1 ,2]]]] 
>>> [sum(x, []) for x in list1] 
[[0, 0, 0, 1, 0, 2]] 
>>> [sum(x, []) for a in list2 for x in a] 
[[0, 0, 0, 1, 0, 2], [1, 0, 1, 1, 1, 2]] 
>>> 
+0

謝謝你的回答,雖然有效,但速度很慢 –

1

鑄造你的數據篩選爲numpy.array,你可以使用reshape

import numpy as np 
t = np.array([[[[0, 0] , [0, 1], [0, 2]], [[1, 0], [1, 1], [1 ,2]]]]) 
print t.shape # (1, 2, 3, 2) 
t = np.reshape([1, 2, 6]) # merging the last 2 coordinates/axes 

將第二個列表弄平如你所願。

(因爲在這兩種情況下,你要合併的最後一個軸),這兩個名單工作的代碼是:

t = np.array(yourList) 
newShape = t.shape[:-2] + (t.shape[-2] * t.shape[-1],) # this assumes your 
# arrays are always at least 2 dimensional (no need to flatten them otherwise...) 
t = t.reshape(t, newShape) 

最關鍵的事情是保持形狀不變,直到最後2軸(因此 t.shape[:-2]),但是到最後兩個軸合併到一起(使用長度t.shape[-2] * t.shape[-1]的軸線)

我們正在創建由這兩個元組級聯新的形狀(因此相乘後額外的逗號)。

編輯:np.reshape() doc是here。重要參數是輸入數組(您的列表,作爲數組進行投射)以及我稱之爲newShape的元組,它表示沿新軸的長度。

+0

你能解釋一下如何使用reshape(),尤其是參數的含義在這種情況下? –

+0

我得到了這個錯誤:':不能乘以類型爲'tuple'的非int的序列 –

+0

好吧,但現在我得到了:':只有長度爲1的數組可以轉換爲Python標量' –

相關問題