在 Python 中按集合成员资格对整数进行分组

发布于 2024-11-08 07:21:40 字数 533 浏览 1 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱,才寂寞 2024-11-15 07:21:40

我什至想到它的效率,但它非常紧凑:

 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文