Combination/Permutation python 开启或关闭 4 个主题

Combination/Permutation 4 topics on or off in python

我不确定这是组合题还是排列题

我有一个包含 4 个主题的列表

topics = ['A', 'B', 'C', 'D']

这些主题中的每一个都可以有开启或关闭状态

state = [1, 0]

我该如何列出所有可能的组合?

我在想这样的结果(例如 df 不一定是 df):

     A B C D
0    1 1 1 1
1    0 0 0 0
2    1 0 0 0
3    1 0 0 1
import itertools
list(itertools.product([0, 1], repeat=len(topics)))

这也将以递增的顺序给出它们作为二进制数

使用来自itertools recipes

powerset食谱

在幂集中,有 2**len(list) 个结果(这里列表中有 4 个项目,有 2**4 == 16 个结果)。

from itertools import combinations, chain

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

for pset in powerset(['A','B','C','D']):
    print(pset)

打印:

()
('A',)
('B',)
('C',)
('D',)
('A', 'B')
('A', 'C')
('A', 'D')
('B', 'C')
('B', 'D')
('C', 'D')
('A', 'B', 'C')
('A', 'B', 'D')
('A', 'C', 'D')
('B', 'C', 'D')
('A', 'B', 'C', 'D')