[英]Find difference between two values?
我有一個隨機數據集,我想知道是否有可能找到所有點之間的差大於某個常數的點集。 點是否不連續並不重要,只要相應值之間的差大於該常數即可。
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)
。
但是,要將其應用於您的問題,將需要一個示例,說明您擁有的數據和所需的結果。 例如,可能需要一些規范化,或者畢竟您不處理集合。
您可以(可能應該)使用itertools.permutations
,而無需嵌套循環。
例如:如果我們要從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)]
對的,這是可能的。 就像這樣:
sets = []
for item1 in dataset:
for item2 in dataset:
if abs(item1 - item2) > somevalue):
sets.append((item1, item2))
您創建一個sets
列表,該列表將保留絕對差大於somevalue
的值對。 然后,將包含這些項目的值的集合附加到sets
。
編輯:列表sets
是一個可變的對象,如果您希望它是不可變的,則此代碼對您不起作用。
使用嵌套循環
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, j
和j, i
都添加到結果中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.