【问题标题】:Removing tuples that contain specific elements (cards)删除包含特定元素(卡片)的元组
【发布时间】:2016-11-03 06:00:35
【问题描述】:

假设我有一张卡片列表(元组)。例如,

[('H[A]', 'S[2]'), ('H[A]', 'H[3]'), ('H[A]', 'H[4]')....]

H[A]:红桃 A 和 S[2]:黑桃 2。

卡片列表表示您可以从一副 10 张卡片中取出的一对卡片的所有独特组合。我所做的只是列出所有独特的组合,将它们洗牌并从中抽出1个组合(每个组合都有一对牌)

def chooseobjects(r):
    """
    Finds all unique pairs of cards in a deck of 10 cards.
    Mathematically, this is just nCr. i.e., 10C2 is 10 Choose 2.
    """
    results = list(itertools.combinations(["H[A]","H[2]","H[3]","H[4]","H[5]",
                                           "S[A]","S[2]","S[3]","S[4]","S[5]",
                                            ],r))
    return results

def draw(n,cards):
    """
    Draw n pair(s) of card from all the unique pairs generated from chooseobjects method.
    """
    random.shuffle(cards)
    return [cards.pop() for k in range(n)]

cards=chooseobjects(2) 
print("These are all the different unique combinations: "'\n',cards)
n=1
ding=draw(n,cards)
print("We randomly drew this pair: "'\n', ding)
print("The remaining unique pairs: "'\n',cards)

我现在想做的是删除/删除那些包含“H[2]”或“S[4]”的对。然后返回一个更新的列表。

有什么想法吗?让我知道!非常感谢任何帮助!

编辑: -尝试-

[p for p in cards if "H[2]" not in p and "S[4]" not in p]

上面的代码返回一个元组列表,其中 H[2] 和 S[4] 不存在。

有没有更优雅的方式将 H[2] 和 S[4] 隐式传递到列表推导中,而不必显式声明/声明它们?告诉我!

编辑 2: -已解决-

因此,解决方案是将两个元素 'H[2]' 和 'S[4]' 附加到列表 j 中。

j=[j for item in ding for j in item]

注意列表 j 中的每个元素都是字符串类型。即,

j[0] = H[2]
j[1] = S[4]

然后我们创建一个列表推导来遍历“卡片”列表中的每个元组。如果 j[0] 和 j[1] 没有出现在元组中,我们将它们全部附加到一个新列表中!

[p for p in cards if j[0] not in p and j[1] not in p]

【问题讨论】:

  • 您在哪里尝试这样做?
  • 我的尝试很糟糕,因此没有将其包含在此处。但是,我会在回家后立即添加尝试。
  • 刚刚添加了我的尝试!任何帮助都会很棒。谢谢

标签: python list python-3.x tuples playing-cards


【解决方案1】:

因此,解决方案是将两个元素 'H[2]' 和 'S[4]' 附加到列表 j 中。

j=[j for item in ding for j in item]

注意列表 j 中的每个元素都是字符串类型。即,

j[0] = H[2]
j[1] = S[4]

然后我们创建一个列表推导来遍历“卡片”列表中的每个元组。如果 j[0] 和 j[1] 没有出现在元组中,我们将它们全部附加到一个新列表中!

[p for p in cards if j[0] not in p and j[1] not in p]

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    cards = [(card1, card2) for (card1, card2) in cards if card1 not in ding[0] and card2 not in ding[0]]
    

    【讨论】:

    • card1card2 都不会在 ding 中,因为 ding 包含元组,而 card1card2 是这些元组的元素。例如,'H[2]' in [('H[2]', 'S[4]')]False
    • 所以,我认为这里的总体思路是访问两个元素“H[2]”和“S[4]”。然后遍历卡片列表并检查这些元素是否存在。如果他们这样做,删除/删除元组。
    • 所以,他只需要签入ding[0]
    【解决方案3】:

    假设您将列表中的元组组合存储为my_list。您可以使用 list comprehension 将列表过滤为:

    new_list = [card_pair for card_pair in my_list if 'H[2]' not in card_pair and 'S[4]' not in card_pair]
    

    这里new_list 将包含所有没有H[2]S[4] 的对。

    【讨论】:

    • 您正在使用原始完整列表副本中的索引来访问更改列表。第一次删除后,您将开始获得不正确的索引。在您从中删除内容的列表的长度变得比您正在查看的索引短后,您将在下次尝试删除时收到 IndexError
    • @TigerhawkT3:是的,你是对的。更新了答案
    猜你喜欢
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2014-11-08
    • 2016-02-15
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    相关资源
    最近更新 更多