2017-09-04 6 views
0

oopに新しく追加されました。私はget_valueメソッドを完了しようとしています。dictのキーとobjectを比較し、TypeError: 'Card'オブジェクトは反復不可能です

VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10} 

class Hand: 
def __init__(self): 
    self.cards = [] # create Hand object   

def __str__(self): 
    self.string = '' 
    for card in self.cards: 
     self.string += card.__str__() 
    return 'Hand contains ' + self.string # return a string representation of a hand 


def add_card(self, card): 
    self.cards.append(card) # add a card object to a hand 

def get_value(self): 
    self.x = [] 
    for key, value in VALUES2.items(): 
     for card in self.cards: #also tried for card in h.cards if h = Hand() 
      test2 = map(lambda each:each.strip("C"), card) #line 57     
      if key in test2: 
       self.x.append(value) 
    hand_value = sum(self.x) 
    return hand_value 

私が実行すると、次のようになります。57行目:TypeError: 'Card'オブジェクトは反復可能ではありません。

c2 = Card("C", "2") 
test_hand = Hand() 
test_hand.add_card(c2) 
print test_hand 

Hand contains C2 

おかげで、物事のコレクションに関数を適用することにより、

答えて

0

map作品を作り出します。 1つのCardインスタンス(つまりTypeError)でこのオブジェクトを使用しようとしています。mapはオブジェクトのコレクションを2番目の引数として想定しています。

あなたは辞書のいくつかの性質を利用して、このようなあなたの方法を簡素化することができます。

def get_value(self): 
    # self.x = [] - you don't need self here, as this value is only 
    # local for this method. 

    value = 0 
    for card in self.cards: 
     for item in str(card): # convert the card to its string representation 
           # giving us 'C2', then loop through each character 
           # of that string value; store it as item 

      value += VALUES2.get(item, 0) # Use the .get method of dictionaries 
             # to lookup item, if it exists, return 
             # the value, otherwise return 0 
             # Add the value to the total. 

    return value # return the sum of all values collected 
関連する問題