洗牌堆栈的 Pythonic 方式

Pythonic way to shuffle stacks

我想随机排列任意数量的堆栈中的元素。比如我有3个栈,栈的元素如下 [ ["A", "C"] , ["B" , "D" ] ["E"] ]

洗牌后(从一个堆栈的顶部移除并插入另一个堆栈的顶部)我得到 6 种可能的状态:

[[['A'], ['B', 'D', 'C'], ['E']], 
 [['A'], ['B', 'D'], ['E', 'C']],
 [['A', 'C', 'D'], ['B'], ['E']],
 [['A', 'C'], ['B'], ['E', 'D']], 
 [['A', 'C', 'E'], ['B', 'D'], []],
 [['A', 'C'], ['B', 'D', 'E'], []]]

我已经编写了一个方法来执行此操作,但我认为这不是 pythonic 方法。执行此操作的 pythonic 方法是什么?

您可以在下面找到我的代码。

def childstates( self ):
    children = []
    # iterate over self state one stack at a time
    for x in self.state:
        #if stack is not empty store the top element
        if len(x) > 0:
            ele = x[-1]
            visited = set([]) 
        # if stack is empty move to the next stack
        else:
            continue
        # each stack will produce n-1 combinations
        for i in range( len( self.state ) - 1 ):
            added = False
            index = 0
            # l2 => new list for each combination
            l2 = copy.deepcopy( self.state)
            for y in l2:
                if x == y:
                    y.pop()
                    index += 1
                    continue

                elif index in visited or added == True:
                    index += 1
                    continue
                else:
                    visited.add( index )
                    y.append( ele )
                    added = True
                    index += 1

            children.append( l2 )
    return children

似乎您可以通过两个 for 循环更轻松地完成此操作,分别遍历从哪个堆栈弹出和压入哪个堆栈:

import itertools
import copy
stacks = [["A", "C"], ["B" , "D" ], ["E"]]
children = []
for i in range(len(stacks)):
    for j in range(len(stacks)):
        if i == j:
            continue
        cur_stack = copy.deepcopy(stacks)
        cur_stack[j].append(cur_stack[i].pop())
        print cur_stack
        children.append(cur_stack)

结果:

[['A'], ['B', 'D', 'C'], ['E']]
[['A'], ['B', 'D'], ['E', 'C']]
[['A', 'C', 'D'], ['B'], ['E']]
[['A', 'C'], ['B'], ['E', 'D']]
[['A', 'C', 'E'], ['B', 'D'], []]
[['A', 'C'], ['B', 'D', 'E'], []]