2017-04-26 238 views
0

如何從Python 3中重複刪除列表中的項目?對於我的代碼工作的第一個項目,但如果我嘗試應用再次刪除項目的方法,它會生成TypeError。這裏是我一起工作的代碼:反覆從類對象(Python)中的列表中刪除項目

十一點遊戲

from random import choice 

class Black_jack_deck(object): 

    def __init__(self, full_deck=(([str(i) for i in range(2,11)]+["A","J","Q","K"])*4*6)): #a deck of 312 cards containing 6* 52 french cards 
     self.full_deck = full_deck 

    def draw(self, draw=True): 
     self.draw = choice(self.full_deck) #I use choice to simulate the dealer drawing a card from the top of a mixed card staple 
     return self.draw 
     self.full_deck = (self.full_deck).remove(self.draw) 


deck = Black_jack_deck() 

當我嘗試調用deck.draw()第二次所產生的誤差是這樣的:

Traceback (most recent call last): 
    File "<pyshell#1>", line 1, in <module> 
    deck.draw() 
TypeError: 'str' object is not callable 

注:即使沒有choice()功能,例如在混洗的full_deck上使用pop(),也會發生相同的錯誤。

+0

請發佈格式正確的代碼。在Python中,空格在語法上很重要,並且按照這種方式,它不起作用。 – Morgoth

+1

您似乎有一個名爲'self.draw'的函數和變量。你如何期待Python知道你的意思? – Craig

+1

Python「知道」它是哪一個:它是最後一個被設置的。你會*覆蓋另一個。 –

回答

1

您正在用繪製的卡片覆蓋Black_jack_deck.draw()方法。因此關於deck.draw()的錯誤是'str' objectis not callable

這是一個較短的版本。你需要記住鞋子上的抽獎卡嗎?我刪除了布爾參數draw(),因爲我不知道它爲什麼在那裏。

In [94]: class CardShoe(object): 
    ...:  def __init__(self, num_decks=6): 
    ...:   self.cards = list('A23456789JQK' * 4 * num_decks) 
    ...:   random.shuffle(self.cards) 
    ...: 
    ...:  def draw(self): 
    ...:   self.last_card_drawn = self.cards.pop() 
    ...:   return self.last_card_drawn 
    ...: 

In [95]: shoe = CardShoe() 

In [96]: shoe.draw() 
Out[96]: '2' 

In [97]: shoe.draw() 
Out[97]: '8' 
+0

與記憶的東西將在晚些時候。現在我只是想讓卡片繪製工作。有了布爾參數,我認爲這是必要的。感謝你的回答,它非常幫助我:-) –