python - 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]
解决方案
简而言之,将所选卡片的分数相加
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 最高;然后按花色顺序:黑桃(最高)、红心、菱形和梅花
推荐阅读
- sql - 从 pipelinedb 连接到 kafka 时如何提供 SASL/PLAIN 凭据?
- selenium - 在 Selenium 中,当我使用带有两个 ByXPath 的 ByChained 以及仅使用一个 ByXPath 定位器时,为什么会得到不同的结果?
- r - 渲染 rmarkdown 文档时保留辅助 TeX 文件
- karate - karate-gatling:如何从模拟响应时间中排除设置/创建?
- python - 创建一个networkx加权图并找到权重最小的2个节点之间的路径
- html - 如何使用 bootstrap 命令在 jumbotron 容器中将一行居中,尽管它的宽度和高度是?
- c# - 当任务有继续但没有线程等待它时,所有活动请求都会挂起
- javascript - Javascript命名空间解释
- javascript - 使用 Javascript 对从 Google 表格导入的表格值进行排序
- haskell - 需要一个函数来验证密码是否强