m0_56035801 2021-03-19 20:55 采纳率: 75%

# 遍历时使用sorted排序并调用类的方法出现NameError

``````import collections
from random import choice

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

class FrenchDeck:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.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, position):
return self._cards[position]

suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)

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

deck = FrenchDeck()

for card in sorted(deck, key=spades_high): #doctest: +ElLIPSIS
print(card)``````

``````Traceback (most recent call last):
File "C:/Users/86199/Desktop/wqe.py", line 32, in <module>
for card in sorted(deck, key=spades_high): #doctest: +ElLIPSIS
NameError: name 'spades_high' is not defined

Process finished with exit code 1``````
• 写回答

#### 1条回答默认 最新

• herosunly Python领域优质创作者 2021-03-19 21:21
关注

``````import collections

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

class FrenchDeck:

ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.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, position):
return self._cards[position]

suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)

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

deck = FrenchDeck()
for card in sorted(deck, key=spades_high): #doctest: +ElLIPSIS
print(card)
``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 evo评估时曲线出现问题
• ¥15 eNSP拓扑图配置实验
• ¥20 有没有兄弟会替换fmod studio的.bank文件内的音效？
• ¥20 如何解决访问网址被屏蔽的情况
• ¥15 本地运行的vue2项目，使用内网穿透，前端界面一直转圈圈
• ¥20 powerbuilder datawindow控件导出Excel数据，可不可以不自动覆盖原数据，而是在后面新插入入数据。
• ¥100 无轴承永磁同步电机控制
• ¥15 eps里添加本地倾斜模型
• ¥15 telegram 问题
• ¥15 nrf52810-c三个a 程序