我有一副牌,我拉了一只手。我被眼前的景象吓了一跳,我想丢掉上面提到的牌,换一只新牌。我该怎么做?
基本上,我似乎不能丢弃元组。我不能deck.remove(hand)
它们,而且我似乎找不到其他方法来摆脱它们。有什么建议吗?我的代码在下面。(我已经看到了更好的方法来做卡片,但我在Python方面还不够好,还不能使用类。我只是想找到一种方法来从卡片组中删除我手中的任何元组。)
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
使用集合运算。简单解决方案
deck = tuple(set(deck) - set(tuple(hand))) # removes all the tuples from deck which are there in hand
您不能更改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)
# Removed hand from deck.
deck = tuple(card for card in deck if card not in set(hand))
你可以做一些类似的事情来添加项目。如果这种情况经常发生,最好使用可变容器,比如list
或dict
,这样你就可以在不重新创建整个内容的情况下修改它们的内容。