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] に変更する必要があります。

しかし、私がデッキを呼び出すたびに、それは変わりません...

4

2 に答える 2

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]
于 2013-10-27T07:18:38.377 に答える
1

deck引数として渡されるのは、参照のコピーを持つ単なる変数であるため、割り当てるときに

deck = ....

新しいオブジェクトを作成し、その参照をデッキ変数に割り当てます。これらはc++ の意味での参照ではなく、常に参照のコピーです。

考えられる回避策の1つは、使用することです

deck[:] = ...

参照値だけでなく、オブジェクトのコンテンツを更新します

于 2013-10-27T07:19:50.800 に答える