2016-11-13 8 views
0

次のコードは機能しませんが、関数がリスト[カード]にアクセスしたり認識しなかったりすると思われます。一方、関数内にリスト[cards]を置くと、コードは完全に機能します。私はメインコードに置かれた変数はグローバルであり、関数で宣言された変数はローカルであると仮定していました。Python - 関数内のリストの参照

#!/usr/bin/python 

import random 

cards = ['A︎♣︎︎', '2︎♣︎︎', '3︎♣︎︎', '4︎♣︎︎', '5︎♣︎︎', '6︎♣︎︎', '7︎♣︎︎', '8︎♣︎︎', '9︎♣︎︎', '10︎♣︎︎', 'J︎♣︎︎', 'Q︎♣︎︎', 
     'K︎♣︎︎', 'A♠︎', '2♠︎', '3♠︎', '4♠︎', '5♠︎', '6♠︎', '7♠︎', '8♠︎', '9♠︎', '10♠︎', 'J♠︎', 
     'Q♠︎', 'K♠︎', 'A︎♥︎', '2︎♥︎', '3︎♥︎', '4︎♥︎', '5︎♥︎', '6︎♥︎', '7︎♥︎', '8︎♥︎', '9︎♥︎', '10︎♥︎', 
     'J︎♥︎', 'Q︎♥︎', 'K︎♥︎', 'A︎♦︎︎', '2︎♦︎︎', '3︎♦︎︎', '4︎♦︎︎', '5︎♦︎︎', '6︎♦︎︎', '7︎♦︎︎', '8︎♦︎︎', '9︎♦︎︎', 
     '10︎♦︎︎', 'J︎♦︎︎', 'Q︎♦︎︎', 'K︎♦︎︎'] 

# define function 


def sort_cards(hand): 

    temp = [] 
    for n in range(0, 7): 
     temp.append(cards.index(str(hand[n]))) 

    # sort cards 
    temp.sort() 
    hand = [] 

    # fetch card according to index and assign to hand 
    for c in temp: 
     hand.append(cards[c]) 

    return hand 


# copy cards list to working list 

rem_cards = cards 

# initiate players card list 

player1 = [] 
player2 = [] 
player3 = [] 

# define variable 
# 7 cards per player 

deal = 7 

while deal != 0: 

    # get a card from rem_cards and assign to player1 
    card = rem_cards[random.randint(0, len(rem_cards) - 1)] 
    player1.append(card) 
    # remove card from deck 
    rem_cards.remove(card) 

    card = rem_cards[random.randint(0, len(rem_cards) - 1)] 
    player2.append(card) 
    rem_cards.remove(card) 

    card = rem_cards[random.randint(0, len(rem_cards) - 1)] 
    player3.append(card) 
    rem_cards.remove(card) 

    deal -= 1 


print(sort_cards(player1)) 
print(sort_cards(player2)) 
print(sort_cards(player3)) 
print("No of cards left in the deck is ", len(rem_cards)) 

私の提案は何か間違っていますか?

+4

「動作しません」という意味ですか?エラーや予期しない出力が出ますか? –

+0

関数内でグローバル変数を使用する場合は、その変数を 'global'キーワードの関数本体に宣言してください。 –

+0

ちょうどいいヒント:' random.randint(0、len)でインデックスを作成するのではなく、 'random.choice' (rem_cards) - 1) ' –

答えて

1

あなたのコメントを見てみましょう:はリストのコピーを作成していないこのコード

# copy cards list to working list 

rem_cards = cards 

を、それが元のリストにアクセスすることができたの下に別のを作成します。 rem_cardsを変更するたびに、cardsが変更されます。従って、rem_cards.remove(card)実際にははからカードを削除します!あなたがリストをコピーする場合は

copy.[deep]copy使用:

import copy 

# copy cards list to working list 

rem_cards = copy.deepcopy(cards) # if cards could contain other lists 
rem_cards = copy.copy(cards) # create a simple shallow copy 
rem_cards = cards[:] # you may create shallow copies without the copy module 
+1

'deepcopy'の必要はありません。 –

+1

を作成するか、次のようなコピーを作成してください: 'rem_cards = cards [:]' –

+0

@ juanpa.arrivillaga、これはちょうどリストに他のリストが含まれている場合の予防策です – ForceBru

0

これもリストをコピーしませんcopy.deepcopy

rem_cards = cards[:] 
+0

OPはディープコピーを望んでいる可能性があります。 – direprobs

+0

@direprobsなぜOPはディープコピーを必要としますか? –

+0

@direprobs深いコピーリスト項目は必要ありませんstring – Serjik

0
rem_cards = cards 

を使用せずに、あなたの問題を解決しますが、エイリアスを作成するだけです。それはする必要があります

rem_cards = list(cards) 
関連する問題