2016-11-13 50 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)