2013-10-27 81 views
0

我的代碼如下(我不知道爲什麼它不縮進):爲什麼我的代碼不會改變列表?

def move_joker_2(deck): 

#start checking every card in the deck until the position of 
#JOKER2 is found 

#we start from position 0 
position = 0 

while deck [position] != JOKER2: 
    position = position + 1 

#the new position for JOKER2 
if position < len (deck) - 3: 
    new_position = position + 2 
elif position == len (deck) - 2: 
    new_position = 0 
else: 
    new_position = 1 

#to reorganize deck, we need 2 things 
# 1.) a list of the cards above JOKER2 after moving the cards 
# 2.) a list of the cards below JOKER2 after moving the cards 

#depending of new_position, there are 3 possible new decks 

if new_position == 0: 
    #no cards above, JOKER2 will become the top card 
    cards_above = [] 
    #every other card will be below it 
    cards_below = deck 
    #remove JOKER2, since we moved it 
    cards_below.pop(position) 

elif new_position == 1: 
    #the only card above JOKER2 will be the top card 
    cards_above = [deck[0]]  

    #every other card up except the last one will be below it 
    cards_below = deck [new_position:len(deck)-1] 

else: 

    cards_above = deck[0:new_position+1]  
    #remove JOKER2, since we moved it 
    cards_above.pop(position) 
    cards_below = deck [new_position+1:] 

#final deck 
deck = cards_above + [JOKER2] + cards_below 

我的代碼接收字符串列表和變異它到底...

但爲什麼它不改變原始列表? 例如:

甲板= [1,3,27,8,9] move_joker_2(甲板)

應該更改列表,考慮到JOKER2是27,於: [1,3 ,8,9,27]

但每當我打電話甲板它並沒有改變......

+0

邊評論有關代碼:你確定你真的需要三種不同的情況? – 6502

回答

6

deck = cards_above + [JOKER2] + cards_below不會改變deck的內容。

它做了一個新的列表和deck參考新列表。

改變桌面使用片符號的內容,如deck[:] = cards_above + [JOKER2] + cards_below

>>> def f1(deck): 
...  deck = [1,2,3] # This does not change the `deck` passed. 
         # This just create a local variable `deck`. 
... 
>>> def f2(deck): 
...  deck[:] = [4,5,6] # This change the `deck` passed. 
... 
>>> deck = [0] 
>>> f1(deck) 
>>> deck 
[0] 
>>> f2(deck) 
>>> deck 
[4, 5, 6] 
1

deck作爲參數傳遞僅僅是一個參考的副本變量,所以當你分配

deck = .... 

創建新的對象,並指定其引用到甲板可變。這些是而不是在C++意義上的引用,這些是總是引用的副本。

一個opssible外觀圖釋是使用

deck[:] = ... 

其中更新對象的內容,而不只是參考值

+0

太棒了,我不知道這種分裂形式的存在。然而,我注意到爲什麼我的列表沒有變化,並正在實現一個while循環來單獨替換每個字符,但是這看起來更好。 – OHHH

相關問題