I have a deck of cards, and I take a hand. Appalled by what I see, I want to discard the aforementioned cards and take a new hand. How do I go about this?
Basically, I can't seem to discard the tuples. I can't deck.remove(hand)
them, and I can't seem to find another way to get rid of them. Any suggestions? My code is below. (I've seen better ways to do the cards, but I'm not good enough at Python yet to use classes. I just seek a way to remove any tuples in my hand from the deck.)
import random
import itertools
suits = (" of Hearts", " of Spades", " of Clubs", " of Diamonds")
ranks = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace")
deck = tuple("".join(card) for card in itertools.product(ranks, suits))
hand = random.sample(deck, 5)
print(hand)
for card in deck:
if card in hand:
# This is what I'm struggling to fill
You can't change deck because it's tuple, but you could recreate it and leave things out. Here's what I mean:
import random
import itertools
suits = (" of Hearts", " of Spades", " of Clubs", " of Diamonds")
ranks = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace")
deck = tuple("".join(card) for card in itertools.product(ranks, suits))
hand = random.sample(deck, 5)
# Removed hand from deck.
deck = tuple(card for card in deck if card not in set(hand))
You could do something similar to add items to it. If this is going to occur frequently, it would probably be better to use a mutable container, like a list
or dict
that would allow you do modify their contents without recreating the whole thing.