首页 > 解决方案 > Python Def函数结果,在Python中调用一个Class函数

问题描述

函数 spades_high 有什么作用?

我不明白这个函数的概念,我想知道它的作用是什么 spades_high 函数在下面给出的代码中做什么?以及 spade_high 函数的目的是什么。(对不起我的英语不好)。非常感谢

import collections


Card = collections.namedtuple('Card',['rank','suit'])


class FrenchDeck:
    ranks = [str(n) for n in range(2,11)] + list("JDKA")
    suits = 'spades diamond clubs heart'.split()

    def __init__(self):
        self.cards = [Card(rank,suit) for suit in self.suits
                      for rank in self.ranks]

    def __len__(self):
        return len(self.cards)

    def __getitem__(self,positions):
        return self.cards[positions]

suit_values = dict(spades = 3,heart = 2,diamond = 1, clubs = 0)

def spades_high(card):
    rank_value = FrenchDeck.ranks.index(card.rank)
    return rank_value * len(suit_values) + suit_values[card.suit]

标签: python

解决方案


简而言之,将所选卡片的分数相加

import collections


Card = collections.namedtuple('Card',['rank','suit'])


class FrenchDeck(): # added brackets
    ranks = [str(n) for n in range(2,11)] + list("JDKA")
    suits = 'spades diamond clubs heart'.split()

    def __init__(self):
        self.cards = [Card(rank,suit) for suit in self.suits for rank in self.ranks]

    def __len__(self):
        return len(self.cards)

    def __getitem__(self,positions):
        return self.cards[positions]

suit_values = dict(spades = 3,heart = 2,diamond = 1, clubs = 0)

def spades_high(card):
    '''
    The variable rank_value is calling the variable "ranks" inside the FrenchDeck class,
    which is getting the index within the list of the card's rank
    '''
    rank_value = FrenchDeck.ranks.index(card.rank) 
    return rank_value * len(suit_values) + suit_values[card.suit]


y = FrenchDeck()
for card in sorted(y,key=spades_high): print(card)

这将按递增顺序给出牌(A 最高;然后按花色顺序:黑桃(最高)、红心、菱形和梅花


推荐阅读