2017-04-23 25 views
2

我記住了一些事情,我覺得很難寫。請原諒我,我現在就跳進去。在兩個列表之間執行操作並跟蹤初始列表

基本上,我有兩個清單列表,每個清單中有不同數量的元素。

L1 = [[1.1,1.2],[1.3,1.4]] 
L2 = [[2.1,2.2],[2.3,2.4],[2.5,2.6]] 

在我行的代碼,我有一個定義函數找到「作爲參數兩個列表之間的最短距離」。例如,在L1 ,所述第一列表它是[1.1,1.2]被提取並且也L2,其被提取[2.1,2.2]的第一列表。然後這個列表都會經過返回值的函數。過程繼續進行,例如[1.1,1.2]然後與[2.3,2.4]進行比較等等,直到沒有更多元素可以比較爲止。從功能上得到的數值,然後添加到列表作爲輸出從哪裏獲得這樣的:

outputL = [values,values,values..... and so on as there are many combinations] 

我現在面臨的問題是不能夠跟蹤其列表從L1的與配對L2中的一些在經歷該功能時。

實施例:

獲得L1的第一列表是[1.1,1.2]和L2是[2.1,2.2] ==>通過函數進==>獲取值==>附加到列表。

現在,而不僅僅是列表中的很多值,我想至少在列表中的值旁邊顯示列表元素,所以我將能夠跟蹤哪些值屬於哪個列表。

expected output would be something like : [values,1.1,1.2, values,1.3,1.4...so on] 

我有一個代碼:

outputL = [] 
for i in L1: 
    for j in L2: 
     results = shortest_distance(i,j) #shortest_distance is the defined function that takes two lists as it's parameter 
     outputL.append(results) 
print(outputL) 
+0

看起來你只是在尋找'枚舉'。 – timgeb

回答

1

你要尋找的是itertools.product

該功能將生成您提供的列表之間所有可能組合的列表。

在自己的2列表例如,這將是這個結果:

list(product(L1, L2)) 
Out[56]: 
[([1.1, 1.2], [2.1, 2.2]), 
([1.1, 1.2], [2.3, 2.4]), 
([1.1, 1.2], [2.5, 2.6]), 
([1.3, 1.4], [2.1, 2.2]), 
([1.3, 1.4], [2.3, 2.4]), 
([1.3, 1.4], [2.5, 2.6])] 

然後,您可以遍歷組合和運行距離函數。在下面的例子中,我使用歐幾里得距離,因爲你沒有提供你自己的距離函數,但你當然可以用你自己的shortest_distance替換euclidean

L1 = [[1.1,1.2],[1.3,1.4]] 
L2 = [[2.1,2.2],[2.3,2.4],[2.5,2.6]] 

from scipy.spatial.distance import euclidean 
from itertools import product 

outputL = [ euclidean(a, b) for pair in product(L1, L2) for a, b in pair ]