【发布时间】: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