如何将已删除的项目表单列表添加到另一个列表



如何将我移除的卡片添加到我的手提手中?抽奖会移除卡片,但我不知道如何将移除的卡片添加到手牌列表中。

import random
deck = ["sA", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "sJ", "sQ",
"sK", "dA", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "dJ",
"dQ", "dK", "cA", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10",
"cJ", "cQ", "cK", "hA", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9",
"h10", "hJ", "hQ", "hK"]
def draw():
if len(deck) == 52:
random_item_from_deck = random.choice(deck)
deck.remove(random_item_from_deck)
random_item_from_deck = random.choice(deck)
deck.remove(random_item_from_deck)
random_item_from_deck = random.choice(deck)
deck.remove(random_item_from_deck)
random_item_from_deck = random.choice(deck)
deck.remove(random_item_from_deck)
random_item_from_deck = random.choice(deck)
deck.remove(random_item_from_deck)

hand=[]
hand.append()

print ("cards in deck : " + str(deck))
draw()
print ("Deck after removal of cards : " + str(deck))
print ("Cards in hand : " + str(hand))

你会为"转移这些卡";。打乱牌组,从顶部取出5张牌:

random.shuffle(deck)
player_hand, remaining_deck = deck[:5], deck[5:]

这能处理你的案子吗?

您可以启动一个空列表并使用其.append()方法

>>> l = ['a', 'b', 'c']
>>> l.append('d')
>>> l
['a', 'b', 'c', 'd']

对于这种情况,您可能还会发现,当您只有一个set时,它是实用的,因为它有方便的成员方法

>>> s = set(('a', 'b', 'c'))
>>> s.remove('a')
>>> s
{'c', 'b'}
>>> s - set(('a', 'c'))
{'b'}

然而,正如@Prune所指出的,洗牌然后切片可能会更干净!

由于牌组中的所有牌都是唯一的,您可以使用它的索引,首先将其转移到手牌上,然后将其移除。

代码:

import random
deck = ["sA", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "sJ", "sQ",
"sK", "dA", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "dJ",
"dQ", "dK", "cA", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10",
"cJ", "cQ", "cK", "hA", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9",
"h10", "hJ", "hQ", "hK"]
hand = [] # define hand here
def draw():
if len(deck) == 52:
for i in range(4): # using a for loop to avoid repetition of statements
random_item_from_deck = random.choice(deck)
hand.append(deck[deck.index(random_item_from_deck)])
deck.remove(random_item_from_deck)

print ("cards in deck : " + str(deck))
draw()
print ("Deck after removal of cards : " + str(deck))
print ("Cards in hand : " + str(hand))

最新更新