Python将8个对象的组合循环为3组,3-3-2

use*_*726 7 python combinations list

假设我有一个包含8个对象的列表,编号为1-8.

这些物体被放入三个盒子中,3个放在一个盒子里,3个放在另一个盒子里,2个放在最后一个盒子里.通过数学,有8C3*5C3 = 560种方法可以做到这一点.我想在那里循环560项.Python有什么方法可以这样做吗?

结果应如下所示:

list=['12','345',678'], ['12','346','578'], ..., etc.
Run Code Online (Sandbox Code Playgroud)

请注意,['12','345','678']并且['12','354',876']为此目的被认为是相同的.

我想制作一个for循环这个列表.Python有什么方法可以这样做吗?

这是我得到的解决方案,但它似乎很难看.

import itertools
for c1,c2 in itertools.combinations(range(8),2):
            l2=list(range(8))
            l2.pop(c2)
            l2.pop(c1)
            for c3,c4,c5 in itertools.combinations(l2,3):
                l3=l2[:]
                l3.remove(c5)
                l3.remove(c4)
                l3.remove(c3)
                c6,c7,c8=l3
                print(c1,c2,c3,c4,c5,c6,c7,c8)
Run Code Online (Sandbox Code Playgroud)

jam*_*lak 2

def F(seq, parts, indexes=None, res=[], cur=0):
    if indexes is None: # indexes to use for combinations
        indexes = range(len(seq))

    if cur >= len(parts): # base case
        yield [[seq[i] for i in g] for g in res]
        return    

    for x in combinations(indexes, r=parts[cur]):
        set_x = set(x)
        new_indexes = [i for i in indexes if i not in set_x]
        for comb in F(seq, parts, new_indexes, res=res + [x], cur=cur + 1):
            yield comb

it = F('12345678', parts=(2,3,3))
for i in range(10):
    print [''.join(g) for g in next(it)]
Run Code Online (Sandbox Code Playgroud)
['12', '345', '678']
['12', '346', '578']
['12', '347', '568']
['12', '348', '567']
['12', '356', '478']
['12', '357', '468']
['12', '358', '467']
['12', '367', '458']
['12', '368', '457']
['12', '378', '456']
Run Code Online (Sandbox Code Playgroud)

另一个例子:

for c in F('1234', parts=(2,2)):
    print [''.join(g) for g in c]
Run Code Online (Sandbox Code Playgroud)
['12', '34']
['13', '24']
['14', '23']
['23', '14']
['24', '13']
['34', '12']
Run Code Online (Sandbox Code Playgroud)