2013-09-24 18 views
1

我使用numpy的與所述代碼加載在三個單獨的文本文件:的Python - 獨特確定哪些文本文件中的元素源自

str = 'data' 
Di = np.loadtxt(str+'i.txt', dtype=np.float64) 
Dj = np.loadtxt(str+'j.txt', dtype=np.float64) 
Dk = np.loadtxt(str+'k.txt', dtype=np.float64) 

文本文件包含與2列和大致6000二維數據行(它們都包含2列,但行數是可變的)。給定一個元素[a,b] - 我如何唯一確定它來自哪個文本文件?

雖然我不能完全確定這些元素是唯一的,但數字[a,b]可能出現在兩個(例如)datai和dataj文本文件中 - 但它不太可能,但我無法完全排除它。

編輯:

加載文本文件,例如,給出了:

Di = [[1 4]  Dj = [[9 4]  Dk = [[2 4]  
     [1 5]   [5 5]    [5 6] 
     [4 5]   [3 6]]    [4 7]] 

     datai.txt   dataj.txt   datak.txt   

所以給出的元素[1 4]輸出將datai.txt,讓我知道[1 4]源於datai.txt文件中的元素。

+0

你能舉個例子嗎? – jabaldonedo

回答

1

喜歡的東西:

import numpy 

Di = numpy.array([[1, 4], [1, 5], [4, 5]]) 

Dj = numpy.array([[9, 4], [5, 5], [3, 6]]) 

Dk = numpy.array([[2, 4], [5, 6], [4, 7]]) 
#>>> 

next(array for array in [Di, Dj, Dk] if ([5, 5] == array).all(1).any()) 
#>>> array([[9, 4], 
#>>>  [5, 5], 
#>>>  [3, 6]]) 

如果你想索引:

next(i for i, array in enumerate([Di, Dj, Dk]) if ([5, 5] == array).all(1).any()) 
#>>> 1 

或名稱:

next(k for k, array in {"Di":Di, "Dj":Dj, "Dk":Dk}.items() if ([5, 5] == array).all(1).any()) 
#>>> 'Dj' 

([5, 5] == array).all(1).any() 

是關鍵部分,它(使用[9 ,4]以供解釋)

[9, 4] == array 
#>>> array([[ True, True], 
#>>>  [False, False], 
#>>>  [False, False]], dtype=bool) 

然後你沿着橫軸穿過all

([9, 4] == Dj).all(1) 
#>>> array([ True, False, False], dtype=bool) 

然後你檢查是否有任何的軸匹配。


next(array for array in [Di, Dj, Dk] if CONDITION) 

作出了僅包含那些滿足條件陣列可迭代,next獲取第一個。如果你不喜歡趕上StopIteration,你可以使用next(..., fallback)

相關問題