python - 如何迭代生成集合中所有可能的元素组合

标签 python python-2.7 numpy set

让 set A=set([1,2,3]) 并设置 B=set() 现在我需要迭代生成所有可能的组合,例如 设置([1]) 设置([2]) 设置([3]) 设置([1,2]) 设置([1,3]) 设置([2,3]) 设置([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 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/

相关文章:

python - 使用memory_profiler在python中进行内存管理

python - 如何通过 scikit-image 调整二值图像的大小?

python - 使用 LinearNDInterpolator 进行外推

python - Jupyter Notebook 定制服务

python - 如何将自定义函数并行应用于数组的成对元素?

python - 时间字符串与当前时间(不含年份)之间的差异

python - 二维 numpy 数组中的比率计算

python - 如何遍历字符串并正确替换 python 中的特定字符?

python - Celery:每个工作人员的 task_acks_late 的不同设置/向 celery 添加自定义选项

python - 获取文本文件中的子目录列表,并在该 txt 文件中附加新的子目录名称