我试图用两个堆栈(集合deque堆栈)定义一个函数,其中第一个项目 弹出堆栈并将其附加到空堆栈,然后将两个堆栈发送到外部函数。 我需要重复此过程两次,但不想重复代码,所以我想知道是否有一些有效的方法来使用while循环 - break语句或迭代器?
import collections
from collections import deque
sentence = [0,1,2,3,4]
stack1 = deque(sentence) # contains sentence
stack2 = deque([]) # empty, awaiting items from stack1
for i in range(0,len(sentence)):
stack1.popleft(i) # pop first item to the left from stack1;0 ([**0**,1,2,3,4])
stack2.append(i) # append it to stack 2; stack2 = ([0])
function(stack1, stack2) #run stack1 and stack2 in external functions
# Repeating
stack1.popleft(i) again #pop (only) once more from stack1; 1 ([**1**,2,3,4])
stack2.append(i) again # append it to stack2; stack2 = ([0, 1])
function (stack1, stack2) # run the external function again
ENDFOR - 结束功能,不再是轮次
答案 0 :(得分:1)
我建议使用一个简单的函数来处理这个问题:
from collections import deque
sentence = [0, 1, 2, 3, 4]
stack1 = deque(sentence)
stack2 = deque([])
print(stack1, stack2)
def do_it(st1, st2):
item = st1.popleft()
st2.append(item)
while stack1:
do_it(stack1, stack2)
# Do some stuff here
do_it(stack1, stack2)
print(stack1, stack2)
输出:
(deque([0, 1, 2, 3, 4]), deque([]))
(deque([]), deque([0, 1, 2, 3, 4]))