(新手)我一直在寻找答案,但是,其他示例不足以满足我的需求。如标题所述,我只是尝试将一个 item(在本例中为 card)从一个列表移至另一个列表。这两个列表称为“牌组”和“手牌”。
一旦您从一个列表中拉出,它就会进入另一个列表,并从其原始列表中删除。
编辑更具体:
deck = [cat, cat, cat, cat, cat, cat, cat, dog, dog, dog, dog, dog, dog, bird, bird, shark, shark, shark]
hand = []
new_deck = []
def startUpCards():
if len(deck) >= 7:
hand = random.sample(deck, 7)
new_deck = [item for item in deck if item not in hand]
deck = list(new_deck)
elif len(deck) < 7:
hand = random.sample(deck, len(deck))
new_deck = [item for item in deck if item not in hand]
deck = list(new_deck)
以上就是您的开始,一切都按预期正确进行。然而,这就是我的问题所在,尽管没有发生错误:
def addNewCard():
if len(deck) > 0:
hand.extend(random.sample(deck, 1))
new_deck = [item for item in deck if item not in hand]
deck = list(new_deck)
else:
sleep(2)
print ("You don't have any more cards in your deck!")
startUpCards()
cardChosen = input("Which card do you want to draw?")
def rmv_hand():
hand.remove(cardChosen)
addNewCard()
`print(hand)`
我发现的问题是,在第一次抽取之后,hand 缩短了 1,这可能意味着它不是从 deck 中抽取的,对吧?
我还看到我的打印字符串 ("You don't have any more cards in your deck!") 正在打印 waaay,超出我的预期!怎么回事?
请您参考如下方法:
您的工作量太大了。使用randrange 按位置 选择卡片。使用pop 将该元素从牌组中移除,并立即将其附加到接收手。这是一个简单的例子:
import random
deck = [1, 2, 3, 4, 5]
hand = [11, 12, 13, 14, 15, 16, 17]
# Choose a random card from the deck *by position*
draw_pos = random.randrange(len(deck))
print "Pulling card #", draw_pos, "from deck to hand"
hand.append(deck.pop(draw_pos))
print deck
print hand
示例输出:
Pulling card # 2 from deck to hand
[1, 2, 4, 5]
[11, 12, 13, 14, 15, 16, 17, 3]
这会让你前进吗?
