2017-06-02 222 views
0

我有一個隨機數據集,我想知道是否可以找到所有的點之間的差異大於某些常數。只要相應值之間的差值大於該常數,這些點是否不連續都沒有關係。找到兩個值之間的差異?

+0

我們需要一個數據示例 – codyc4321

+2

使用經過數據集的嵌套循環並計算元素之間的差異。 – Barmar

+2

請更具體的:添加輸入樣本和所需的輸出 –

回答

3

您可以(也可能應該)使用itertools.permutations,不需要嵌套循環。

E.摹:如果我們想找到10和15之間的數字內容(包括10和15)差大於3:

from itertools import permutations 

numbers = range(10, 16) 
restriction = 3 

filtered_numbers_pairs = [] 
for value, other_value in permutations(numbers, r=2): 
    if value - other_value > restriction: 
     filtered_numbers_pairs.append((value, other_value)) 

print(filtered_numbers_pairs) 

給我們

[(14, 10), (15, 10), (15, 11)] 

或者,如果你需要存儲值指標 - 只需添加enumerate

from itertools import permutations 

numbers = range(10, 16) 
restriction = 3 

filtered_numbers_pairs = [] 
for (index, value), (other_index, other_value) in permutations(enumerate(numbers), r=2): 
    if value - other_value > restriction: 
     filtered_numbers_pairs.append((index, other_index)) 

print(filtered_numbers_pairs) 

給了我們

[(4, 0), (5, 0), (5, 1)] 
+0

非常感謝。這正是我期待的。我真的很感激 –

+0

@alexanderson:不客氣(你也可以[回答投票](https://stackoverflow.com/help/someone-answers)) –

0

是的,這是可能的。 這將是這樣的:

sets = [] 
for item1 in dataset: 
    for item2 in dataset: 
     if abs(item1 - item2) > somevalue): 
      sets.append((item1, item2)) 

您創建一個sets列表,保存值,對其中有一個絕對差值比somevalue大這是要去。然後將包含這些項目值的集合追加到sets

編輯:列表sets是一個可變對象,如果你想這是不可變的,這段代碼將不適用於你。

+0

name'sets'具有誤導性,讓我覺得它包含'set'對象 –

+0

@AzatIbrakov:這不是一個微妙的提示嗎? ;) – Arafangion

+0

它確實包含集合對象,它是集合列表 –

0

使用嵌套循環

diff = [] 
for i, val1 in enumerate(dataset): 
    for j, val2 in enumerate(dataset[i+1:]): 
     if abs(val1 - val2) > some_constant: 
      diff.append((i, j)) 

內環使用數組的一個切片,所以我們不都i, jj, i添加到結果。

3

Python支持集:

>>> a = {1, 2, 3} 
>>> type(a) 
<type 'set'> 
>>> b = {2, 4, 5} 
>>> a-b # Finds all items in a, but not in b. 
set([1, 3]) 
>>> b-a # Finds all items in b, but not in a. 
set([4, 5]) 
>>> (a-b).union(b-a) # Finds the union of both differences. 
set([1, 3, 4, 5]) 

help(set)的文檔。

但是,要將此應用於您的問題,您需要提供一個您擁有的數據和您想要的結果的示例。例如,可能需要一些標準化,或者你可能沒有處理集合。

+0

你所做的被稱爲['symmetric difference'](https://en.wikipedia.org/wiki/Symmetric_difference),'set'有一個[method](https://docs.python.org/2 /library/sets.html#set-objects):'a。symmetric_difference(b)'(但是我不知道OP是在找什麼) –

+0

@AzatIbrakov:的確,運營商似乎已經重載了' - '來做到這一點。 – Arafangion

+0

通過使用「set」這個詞,我很抱歉用錯誤的方式來提問這個問題。我在隨機數據集中尋找一對數字,如果相乘,就會產生一個常數值。我爲我的錯誤道歉。 –

相關問題