类和If语句

时间:2013-12-18 03:49:39

标签: python class

def get_value(self):
        """Get the value on the face card:
           (Jack=11, Queen=12, King = 13), Ace = 1, others are face value 2-10"""

        #List that contains all the face cards that have a special value
        specialJ = ['J']
        specialK = ['K']
        specialQ = ['Q']

        #If the card is a jack, king, or queen, set the return value to 11,13,12
        if self.rank in specialJ:
            int_rank = '11'
        elif self.rank in specialK:
            int_rank = '13'
        elif self.rank in specialQ:
            int_rank = '12'
        #If the card is an ace, set the return value to 1
        elif self.rank == 'A':
            #Set the return value of the card to 1
            int_rank = '1'
        #If the card is not a face card, keep the same return value.
        else:
            int_rank = self.rank

我试图给杰克分配一个值11,女王的值为12,国王的值为13,通过检查是否在特殊列表中找到该卡。这不起作用。我不确定我做错了什么或怎么做。

2 个答案:

答案 0 :(得分:2)

您可以使用列表,例如

def get_value(self):
    my_cards = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
    return my_cards.index(self.rank) + 1

更好的是,如果您要经常访问它,词典将提供更快的查找

def get_value():
    my_cards = {'A': 1, '10': 10, 'K': 13, 'J': 11, 'Q': 12, '3': 3, '2': 2, '5': 5, '4': 4, '7': 7, '6': 6, '9': 9, '8': 8}
    return my_cards.get(self.rank, -1)

答案 1 :(得分:0)

def get_value():
    my_cards = {'A': 1, '10': 10, 'K': 13, 'J': 11, 'Q': 12, '3': 3, '2': 2, '5': 5, '4': 4, '7': 7, '6': 6, '9': 9, '8': 8}
    return my_cards.get(self.rank, -1)

最好的方法