(新手)我已经找到了答案,但是,其他例子还不足以满足我的需求。正如标题所述,我只是想从一个列表到另一个列表中尝试一个item
,或者在这种情况下card
。这两个名单被称为'deck'和'hand'。
从一个列表中拉出后,它会进入另一个列表,并从原始列表中删除。
修改更具体:
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!")
在我预期之前正在打印!发生了什么事?
答案 0 :(得分:1)
你经历了太多的工作。使用 randrange 按位置选择卡片。使用弹出从卡座中删除该元素,立即将其附加到接收方。这是一个简单的例子:
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]
这会让你前进吗?