Python 3.6技术问询:列表随机取项与Blackjack发牌去重实现
Hey there! Let's work through this Blackjack card dealing problem together. I'll show you how to build a function that deals unique cards (no repeats) using Python 3.6 and the random module, based on your existing rank and suit lists.
Step 1: Set up your card lists and full deck
First, let's formalize your rank and suit lists (you probably already have these, but let's make them explicit):
# Your existing rank and suit lists rank_list = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] suit_list = ['♠', '♥', '♦', '♣'] # Or use plain text like 'Spades'/'Hearts' if you prefer
Next, combine these into a full deck of 52 unique cards using a list comprehension—this gives us every possible rank-suit combination:
# Generate complete deck of (rank, suit) tuples deck = [(rank, suit) for rank in rank_list for suit in suit_list]
Step 2: Build the deal function with no repeats
We'll use random.shuffle() to randomize the deck, then list.pop() to remove and return cards. This ensures we never deal the same card twice—once a card is popped, it's no longer in the deck.
import random def deal_new_cards(num_cards=2): """Deals a specified number of unique cards from the deck. Defaults to 2 cards for initial hand.""" # Check if there are enough cards left to deal if len(deck) < num_cards: print("Oops! Not enough cards left in the deck.") return [] # Shuffle the deck for realistic randomness (skip this if you want ordered dealing) random.shuffle(deck) # Grab the required number of cards and remove them from the deck dealt_cards = [] for _ in range(num_cards): dealt_card = deck.pop() dealt_cards.append(dealt_card) return dealt_cards
Step 3: Test the function
Let's see how this works in practice:
# Deal initial hand (2 cards) initial_hand = deal_new_cards() print("Your initial hand:", initial_hand) # Deal 1 more card (hit) hit_card = deal_new_cards(1) print("Hit card:", hit_card) # Check remaining cards in the deck print(f"Cards left in deck: {len(deck)}")
If you want to format cards to look cleaner (like "10♠" or "A of Hearts"), add a quick helper function:
def format_card(card): """Formats a (rank, suit) tuple into a readable string.""" rank, suit = card return f"{rank}{suit}" # Or f"{rank} of {suit}" for longer formatting # Use it when printing your hand formatted_hand = [format_card(card) for card in initial_hand] print("Your initial hand:", formatted_hand)
Key Notes for Python 3.6
random.shuffle()works flawlessly in 3.6—it modifies the deck list in place to randomize order.- List comprehensions and
list.pop()are fully supported, so no compatibility issues here. - By modifying the original deck with
pop(), we guarantee no duplicate deals. To reset the deck for a new round, just re-run the deck generation line:# Reset deck for a new game deck = [(rank, suit) for rank in rank_list for suit in suit_list]
内容的提问来源于stack exchange,提问作者Kipp

