In [1]:
import collections

In [6]:
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]

In [3]:
beer_card = Card('7', 'diamonds')
beer_card


Out[3]:
Card(rank='7', suit='diamonds')

In [7]:
deck = FrenchDeck()
len(deck)


Out[7]:
52

In [8]:
deck[0]


Out[8]:
Card(rank='2', suit='spades')

In [9]:
deck[-1]


Out[9]:
Card(rank='A', suit='hearts')

In [10]:
from random import choice
choice(deck)


Out[10]:
Card(rank='6', suit='hearts')

In [11]:
choice(deck)


Out[11]:
Card(rank='4', suit='clubs')

In [12]:
choice(deck)


Out[12]:
Card(rank='9', suit='clubs')

In [13]:
deck[:3]


Out[13]:
[Card(rank='2', suit='spades'),
 Card(rank='3', suit='spades'),
 Card(rank='4', suit='spades')]

In [14]:
deck[12::13]


Out[14]:
[Card(rank='A', suit='spades'),
 Card(rank='A', suit='diamonds'),
 Card(rank='A', suit='clubs'),
 Card(rank='A', suit='hearts')]

In [15]:
i = 0
for card in deck:
    print(card)
    i += 1
    if i > 5:
        break


Card(rank='2', suit='spades')
Card(rank='3', suit='spades')
Card(rank='4', suit='spades')
Card(rank='5', suit='spades')
Card(rank='6', suit='spades')
Card(rank='7', suit='spades')

In [16]:
Card('Q', 'hearts') in deck


Out[16]:
True

In [17]:
Card('7', 'beasts') in deck


Out[17]:
False

In [18]:
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]

In [20]:
i = 0
for card in sorted(deck, key=spades_high):
    print(card)
    i += 1
    if i > 12:
        break


Card(rank='2', suit='clubs')
Card(rank='2', suit='diamonds')
Card(rank='2', suit='hearts')
Card(rank='2', suit='spades')
Card(rank='3', suit='clubs')
Card(rank='3', suit='diamonds')
Card(rank='3', suit='hearts')
Card(rank='3', suit='spades')
Card(rank='4', suit='clubs')
Card(rank='4', suit='diamonds')
Card(rank='4', suit='hearts')
Card(rank='4', suit='spades')
Card(rank='5', suit='clubs')