设置A=set([1,2,3]) and set B=set()现在,我需要迭代生成所有可能的组合,例如
set([1])set([2])set([3])set([1,2])set([1,3])set([2,3])set([1,2,3])
我公然知道我可以使用itertools的powergenerator配方,但是伪代码以下面的形式用于进一步的条件检查(子集条件和密度条件)

a=set()
b=set([1,2,3])
for i in b-a:
    a=a|set([i])
    for j in a:
        print a-set([j])

        if den(a-set[j])>=0.6:#check density criteria
                # check if a-set([j]) is subset of a on ordering criteria


上面的print语句,即print a-set([j])给出了如下输出

set([])
set([2])
set([1])
set([2, 3])
set([1, 3])
set([1, 2])


但我需要以以下格式输出

set([1])
set([2])
set([3])
set([2, 3])
set([1, 3])
set([1, 2])
set([1,2,3])

最佳答案

您可以使用itertools.combinations

from itertools import combinations

list(combinations(b, 1)) + list(combinations(b, 2)) + list(combinations(b, 3))
#[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

关于python - 如何迭代生成集合中元素的所有可能组合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23535098/

10-11 07:41
查看更多