通过Python中的集合成员资格对整数进行分组 [英] Grouping integers by set membership in Python

查看:301
本文介绍了通过Python中的集合成员资格对整数进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中工作,给定范围范围(s,n)中的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:

示例输入(N = 2套):

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])]

期望输出:

out = [set([10,11]), set([4,5,6]), set([7,8,9]), set([0,1,2,3,12])]

因此在输出中,范围(s,n)中的每个整数恰好出现一次,并且有2 ^ N个集合。在示例中,out [0]包含两个都没有设置的整数。 out [1]包含第二组中的整数,但不包含第一组中的整数。 out [2]包含第一组但不是第二组的整数。最后out [3]包含两个集合共有的整数。

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.

对于2集这很容易......但是我很难接受N集。有没有人有线索?

For 2 sets this is fairly easy... but I'm stumped for N sets. Does anyone have a clue?

推荐答案

我甚至想到这个的效率,但它非常紧凑:

I cringe even thinking about the efficiency of this, but it's pretty compact:

 out = [set(range(x, y))]
 for in_set in input:
    out_diff = [out_set - in_set for out_set in out]
    out_union = [out_set & in_set for out_set in out]
    out = out_diff + out_union

这篇关于通过Python中的集合成员资格对整数进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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