如何在python中动态获取组的组合/排列?

时间:2018-12-06 20:11:22

标签: python combinations permutation itertools cartesian-product

我有3个小组

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

我想要这样的排列/组合

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))

3 个答案:

答案 0 :(得分:1)

给出您的代码,您需要在起始“ bags”的所有可能组合上使用笛卡尔乘积(product):

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)

答案 1 :(得分:0)

在您的示例中,您似乎正在尝试获取每个组的非空子集的乘积。我们可以使用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

答案 2 :(得分:0)

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

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'))]