我想计算一组整数中所有元素之间的绝对差值。我正在尝试abs(x-y)
,其中x
和y
是集合中的两个元素。我希望为所有组合执行此操作,并将结果列表保存在新集中。
答案 0 :(得分:2)
我想计算一组整数(...)中所有元素之间的绝对差值,并将结果列表保存在一个新集合中。
您可以使用itertools.combinations:
s = { 1, 4, 7, 9 }
{ abs(i - j) for i,j in combinations(s, 2) }
=>
set([8, 2, 3, 5, 6])
combinations
返回s中所有组合的r长度元组,无需替换,即:
list(combinations(s, 2))
=>
[(9, 4), (9, 1), (9, 7), (4, 1), (4, 7), (1, 7)]
答案 1 :(得分:0)
由于集合不维护顺序,您可以使用类似ordered-set的内容并迭代到最后但只有一个。
答案 2 :(得分:0)
为了完整起见,这是基于Numpy ndarray
和pdist()的解决方案:
In [69]: import numpy as np
In [70]: from scipy.spatial.distance import pdist
In [71]: s = {1, 4, 7, 9}
In [72]: set(pdist(np.array(list(s))[:, None], 'cityblock'))
Out[72]: {2.0, 3.0, 5.0, 6.0, 8.0}
答案 3 :(得分:0)
这是另一种基于numpy的解决方案:
data = np.array([33,22,21,1,44,54])
minn = np.inf
index = np.array(range(data.shape[0]))
for i in range(data.shape[0]):
to_sub = (index[:i], index[i+1:])
temp = np.abs(data[i] - data[np.hstack(to_sub)])
min_temp = np.min(temp)
if min_temp < minn : minn = min_temp
print('Min difference is',minn)
输出:&#34;最小差异为1&#34;
答案 4 :(得分:0)
这是使用组合的另一种方式:
from itertools import combinations
def find_differences(lst):
" Find all differences, min & max difference "
d = [abs(i - j) for i, j in combinations(set(lst), 2)]
return min(d), max(d), d
测试:
list_of_nums = [1, 9, 7, 13, 56, 5]
min_, max_, diff_ = find_differences(list_of_nums)
print(f'All differences: {diff_}\nMaximum difference: {max_}\nMinimum difference: {min_}')
结果:
All differences: [4, 6, 8, 12, 55, 2, 4, 8, 51, 2, 6, 49, 4, 47, 43]
Maximum difference: 55
Minimum difference: 2