Grouping integers by set membership in Python

☆樱花仙子☆ 提交于 2019-12-23 16:14:12

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/6040919/grouping-integers-by-set-membership-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!