2016-11-13 71 views
0

不用引用列表說下面的代碼無法正常工作,故障或問題似乎是功能不訪問或識別列表[卡]。另一方面,如果我將列表[卡片]放入函數中,則代碼完美地工作。我假定放在主代碼中的變量是全局變量,並且在函數中聲明的變量只是局部變量。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.choice'而不是'random.randint(0,len (rem_cards) - 1)' –

回答

1

在您的評論請看:

# copy cards list to working list 

rem_cards = cards 

此代碼使列表的副本,它創建另一個,其下原來的列表可以訪問。無論何時修改rem_cards,都會修改cards。因此,實際上rem_cards.remove(card)刪除顯卡從cards

如果你要複製的列表,使用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 =卡[:]' –

+0

@ juanpa.arrivillaga,伴你左右,這是以防萬一的列表將包含一次其他名單 – ForceBru

0

這也將解決你的問題,而無需使用copy.deepcopy

rem_cards = cards[:] 
+0

可能OP要深拷貝。 – direprobs

+0

@direprobs爲什麼OP要深度複製? –

+0

@direprobs不需要深度複製列表項是字符串 – Serjik

0
rem_cards = cards 

不會複製列表中,但只是創建一個別名。它應該是

rem_cards = list(cards)