我想计算一组整数中所有元素之间的绝对差。我正在尝试执行 abs(x-y)
,其中 x
和 y
是集合中的两个元素。我想对所有组合都这样做,并将结果列表保存在一个新集合中。
最佳答案
I want to calculate absolute difference between all elements in a set of integers (...) and save the resulting list in a new set.
您可以使用 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)]
关于Python:计算一组整数中所有元素之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37775578/