在 Python 中按集合成员资格对整数进行分组
在 Python 中工作,给定范围 range(s,n) 中的 N 组整数的列表,如何构建一个根据集合成员资格对所有这些整数进行分组的列表?一个例子确实可以帮助我解释:
示例输入(N=2 组):
integerRange = range(0,13)
input = [set([0,1,2,3,7,8,9,12]), set([0,1,2,3,4,5,6,12])]
期望的输出:
out = [set([10,11]), set([4,5,6]), set([7,8,9]), set([0,1,2,3,12])]
因此,在输出中, range(s,n) 中的每个整数只出现一次,并且有 2^N 组。在示例中,out[0] 包含两个集合中都不存在的整数。 out[1] 包含第二组中但不是第一组中的整数。 out[2] 包含第一组中的整数,但不包含第二组中的整数。最后 out[3] 包含两个集合共有的整数。
对于 2 组来说,这相当容易......但我很难过 N 组。有人知道吗?
Working in Python, given a list of N sets of integers from the range range(s,n), how can I build a list that groups all these integers according to their set memberships? An example is really going to help me explain here:
Example input (N=2 sets):
integerRange = range(0,13)
input = [set([0,1,2,3,7,8,9,12]), set([0,1,2,3,4,5,6,12])]
Desired output:
out = [set([10,11]), set([4,5,6]), set([7,8,9]), set([0,1,2,3,12])]
So in the output each integer in range(s,n) appears exactly once, and there are 2^N sets. In the example, out[0] contains the integers that are in neither set. out[1] contains the integers that are in the second set but not the first. out[2] contains the integers that in the first set but not the second. And finally out[3] contains the integers that are common to both sets.
For 2 sets this is fairly easy... but I'm stumped for N sets. Does anyone have a clue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我什至想到它的效率,但它非常紧凑:
I cringe even thinking about the efficiency of this, but it's pretty compact: