Python:计算一组整数中所有元素之间的差异 [英] Python: Calculate difference between all elements in a set of integers

查看:49
本文介绍了Python:计算一组整数中所有元素之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算一组整数中所有元素之间的绝对差.我正在尝试做 abs(x-y) 其中 xy 是集合中的两个元素.我想对所有组合都这样做,并将结果列表保存在一个新集合中.

I want to calculate absolute difference between all elements in a set of integers. I am trying to do abs(x-y) where x and y are two elements in the set. I want to do that for all combinations and save the resulting list in a new set.

推荐答案

我想计算一组整数 (...) 中所有元素之间的绝对差,并将结果列表保存在一个新集合中.

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 长度元组,没有替换,即:

combinations returns the r-length tuples of all combinations in s without replacement, i.e.:

list(combinations(s, 2))
=>
[(9, 4), (9, 1), (9, 7), (4, 1), (4, 7), (1, 7)]

这篇关于Python:计算一组整数中所有元素之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆