如何从元组列表中删除元组?

时间:2019-01-30 19:37:47

标签: python tuples playing-cards

我有一副纸牌,我伸出援手。令我震惊的是,我想丢掉上述卡并换一手新牌。我该怎么办?

基本上,我似乎无法丢弃元组。我无法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

2 个答案:

答案 0 :(得分:1)

使用设置操作。简单的解决方法

deck = tuple(set(deck) - set(tuple(hand))) # removes all the tuples from deck which are there in hand

答案 1 :(得分:0)

您不能更改卡座,因为它是元组,但是您可以重新创建它并忽略所有内容。这就是我的意思:

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))

您可以执行类似的操作以向其中添加项目。如果这种情况经常发生,则最好使用可变容器,例如listdict,该容器允许您修改其内容而无需重新创建整个容器。