如何动态获取 python 中的 combination/permutation 个组?

How can I dynamic get combination/permutation of groups in python?

我有3组

[1,2] [4,5] [a,b]

我要permutations/combinations这样的

1  4  a
1  5  a
1  4  b
1  5  b
2  4  a    
2  5  a
2  4  b
2  5  b
12 4  a
12 5  a
12 4  b
12 5  b
12 4  ab
12 5  ab
1  45 a
2  45 a
1  45 b
2  45 b
1  45 ab
2  45 ab
1  4  ab
2  5  ab
12 45 ab

这个数组可以增长并且不会总是相同的大小,所以排列会增加。

到目前为止我已经知道了。

from itertools import *

bag1 = [1, 2]
bag2 = [4, 5]
bag3  = ['a', 'b']

bags = []

bags.append(bag1)
bags.append(bag2)
bags.append(bag3)

comb = list(product(*bags))

在您的示例中,您似乎在尝试获取每个组的非空子集的乘积。我们几乎可以使用 itertools 逐字执行此操作:首先,定义一个提供非空子集的函数,然后应用乘积。

from itertools import *


def subsets(xs):
    for k in range(1, len(xs) + 1):
        yield from combinations(xs, k)


lst = [[1, 2], [4, 5], ["a", "b"]]

result = list(product(*map(subsets, lst)))

# first few values
# [((1,), (4,), ('a',)),
# ((1,), (4,), ('b',)),
# ((1,), (4,), ('a', 'b')),
# ((1,), (5,), ('a',)),
# ((1,), (5,), ('b',)),

# pretty print
for line in result[:5]:
    line = " ".join("".join(map(str, tok)) for tok in line)
    print(line)


# 1 4 a
# 1 4 b
# 1 4 ab
# 1 5 a
# 1 5 b

给定你的一段代码,你需要使用笛卡尔积(product),对你开始的所有可能组合'bags':

from itertools import product, combinations

def comb_bag( bag):
    new_bag = []
    for n in range( 1, 1+len(bag)):
        new_bag += list( combinations(bag, n))

    return new_bag

bag1 = [1, 2]
bag2 = [4, 5]
bag3  = ['a', 'b']

bags = []

new_bag1 = comb_bag( bag1)
new_bag2 = comb_bag( bag2)
new_bag3 = comb_bag( bag3)

bags.append(new_bag1)
bags.append(new_bag2)
bags.append(new_bag3)

comb = list(product(*bags))

for e in comb:
    print( e)

我认为你想要做的是分别获得每个组的组合,然后获得组的乘积。从那里,如果你想要字符串或其他任何东西,你可以做一些处理。

from itertools import combinations, product

groups = [[1, 2], [3, 4], ['a', 'b']]

# Note you want groups of all sizes:
sub_combs = []
for g in groups:
    group_combs = []
    for r in range(len(g)):
        combs = combinations(g, r+1) #Combinations of all (nonempty) sizes
        group_combs += list(combs)
    sub_combs.append(group_combs)
final_combs = list(product(*sub_combs))

final_combs

[((1,), (3,), ('a',)),
 ((1,), (3,), ('b',)),
 ((1,), (3,), ('a', 'b')),
 ((1,), (4,), ('a',)),
 ((1,), (4,), ('b',)),
 ((1,), (4,), ('a', 'b')),
 ((1,), (3, 4), ('a',)),
 ((1,), (3, 4), ('b',)),
 ((1,), (3, 4), ('a', 'b')),
 ((2,), (3,), ('a',)),
 ((2,), (3,), ('b',)),
 ((2,), (3,), ('a', 'b')),
 ((2,), (4,), ('a',)),
 ((2,), (4,), ('b',)),
 ((2,), (4,), ('a', 'b')),
 ((2,), (3, 4), ('a',)),
 ((2,), (3, 4), ('b',)),
 ((2,), (3, 4), ('a', 'b')),
 ((1, 2), (3,), ('a',)),
 ((1, 2), (3,), ('b',)),
 ((1, 2), (3,), ('a', 'b')),
 ((1, 2), (4,), ('a',)),
 ((1, 2), (4,), ('b',)),
 ((1, 2), (4,), ('a', 'b')),
 ((1, 2), (3, 4), ('a',)),
 ((1, 2), (3, 4), ('b',)),
 ((1, 2), (3, 4), ('a', 'b'))]