I am trying to make a deck of playing cards,where each is a tuple. For example, the card 'Ace of Hearts' with value of 11 would be (‘A’, ‘♥’, 11)
.
How can I generate the entire deck without using classes and save it in a list?
Asked
Active
Viewed 1,430 times
-1

CDJB
- 14,043
- 5
- 29
- 55

cheburashka
- 11
- 4
-
A standard card deck is pretty much just a [Cartesian product of the ranks and suits](https://en.wikipedia.org/wiki/Cartesian_product#A_deck_of_cards). One list comprehension could do it. How you define the "value" might be more interesting; it may be simply a function of the rank. – Fred Larson Jan 06 '20 at 15:42
-
1I'm sure you could, have you tried? – Chris Jan 06 '20 at 15:42
-
I’m voting to close this for being too vague/broad. – AMC Jan 06 '20 at 15:46
2 Answers
0
Using static definitions for the suits, cards, and values, you can do the following to get a list of cards using a list comprehension - the deck list then contains tuples representing cards. You may want to change how the values list is defined according to your requirements.
suits = ['♠', '♥', '♦', '♣']
cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
values = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
deck = [(c, s, v) for c, v in zip(cards, values) for s in suits]

CDJB
- 14,043
- 5
- 29
- 55
-
thank you very much! and if i want to give specific values to a specific card number ? do i have to make a new list of tuples? for example how can i make the value of card Ace of Hearts to be 11? – cheburashka Jan 06 '20 at 16:13
-
This is where classes would be a better approach! You'd need to find the card in `deck` that represents the ace of hearts and change the value. Note that in the current implementation, the value is already `11`. – CDJB Jan 06 '20 at 16:14
0
You could use a collections.namedtuple
, but I do think classes (especially Enum.enum
s are the way to go here):
from collections import namedtuple
Card = namedtuple("Card", ["rank", "suit"])
cards = []
for suit in "\u2660", "\u2665", "\u2666", "\u2663":
for rank in "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K":
cards.append(Card(rank, suit))
print(cards)

Paul M.
- 10,481
- 2
- 9
- 15