Python - Referencing lists in functions -
this question has answer here:
- how clone or copy list? 14 answers
needless following code not work , fault or problem seems function not access or recognise list [cards]. on other hand if place list [cards] within function, code works perfectly. had assumed variables placed in main code global, , variables declared in function local.
#!/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 = [] n in range(0, 7): temp.append(cards.index(str(hand[n]))) # sort cards temp.sort() hand = [] # fetch card according index , assign hand c in temp: hand.append(cards[c]) return hand # copy cards list working list rem_cards = cards # initiate players card list player1 = [] player2 = [] player3 = [] # define variable # 7 cards per player deal = 7 while deal != 0: # card rem_cards , assign player1 card = rem_cards[random.randint(0, len(rem_cards) - 1)] player1.append(card) # remove card 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 deck ", len(rem_cards))
any suggestions or concept wrong?
take @ comments:
# copy cards list working list rem_cards = cards
this code does not make copy of list, creates name, under original list accessed. whenever modify rem_cards
, cards
modified. thus, rem_cards.remove(card)
removes card cards
!
if want copy list, use copy.[deep]copy
:
import copy # copy cards list working list rem_cards = copy.deepcopy(cards) # if cards contain other lists rem_cards = copy.copy(cards) # create simple shallow copy rem_cards = cards[:] # may create shallow copies without copy module
Comments
Post a Comment