2014-02-20 39 views
1

我想定義一個函數與兩個堆棧(集合deque堆棧)從第一個 堆棧彈出並附加到一個空的堆棧,然後這兩個堆棧是發送到外部功能。 我需要重複這個過程兩次,如下所示,但不想重複代碼,所以我想知道是否有一種有效的方法來做到這一點while循環 - 斷言或迭代器?For循環堆棧和外部函數沒有重複popleft()

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 - 端功能,沒有更多輪

+1

爲什麼不直接定義函數需要兩個堆棧和'i',並且完成了你剛做了兩次的操作。所以,本質上是一個外部函數調用。 –

+0

堆棧內容影響函數中的值,所以我可以像你說的那樣將stack1.popleft()和stack2.append()添加到函數中,但是我將不得不重複使用堆棧函數(stack1,stack2 ), 再一次。 – user1749431

+0

'deque.popleft()'不帶任何參數。你可能是想做'stack2.append(stack1.popleft())'? –

回答

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])) 
+0

謝謝,非常適合兩輪。 – user1749431