涉及知识点
- collections — Container datatypes
- collections.namedtuple
- 特殊方法
- 切片操作
- 反向迭代
- 排序函数(sorted)
代码
import collections # collections — Container datatypes
# namedtuple() Factory Function for Tuples with Named Fields
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]
beer_card = Card('7', 'diamonds')
print('beer_card', beer_card)
# 通过特殊方法 __getitem__ 进行取值
deck = FrenchDeck()
print('deck[-1]', deck[-1])
# 切片操作获取值,通过特殊方法 __getitem__ 进行取值
print('deck[:3]', deck[:3]) # 获取最前面 3 张牌
print('deck[12::13]', deck[12::13]) # 抽出索引为 12 的那张牌,然后每隔 13 张牌拿一张
# 反向迭代
for card in reversed(deck):
print('card_reversed', card)
# 排序扑克
suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0) # 生成排序字典
def spades_high(card):
rank_value = FrenchDeck.ranks.index(card.rank)
return rank_value * len(suit_values) + suit_values[card.suit]
for card in sorted(deck, key=spades_high):
print('spades_high,card', card)
参考资料
- Fluent Python
- Python 官方文档
总结
“等到用到的时候我再去学。”
可以学的东西就被局限到你需要用到这个条件下
。