Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 为什么我的程序在4个列表中至少有1个变为空时崩溃?_Python 3.x - Fatal编程技术网

Python 3.x 为什么我的程序在4个列表中至少有1个变为空时崩溃?

Python 3.x 为什么我的程序在4个列表中至少有1个变为空时崩溃?,python-3.x,Python 3.x,我正在用python创建纸牌游戏“战争”。在战争中,你将所有52张牌分配给玩家。我遇到的问题是,当一个诉讼清单变为空时,程序就会崩溃。我试图通过说suit=random.choice(poss_suits)来解决这个问题,在之后,除了索引器:,但这不起作用。有什么想法吗 Diamonds = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King'] Hearts = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 1

我正在用python创建纸牌游戏“战争”。在战争中,你将所有52张牌分配给玩家。我遇到的问题是,当一个诉讼清单变为空时,程序就会崩溃。我试图通过说
suit=random.choice(poss_suits)
来解决这个问题,在
之后,除了索引器:
,但这不起作用。有什么想法吗

Diamonds = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King']
Hearts = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King']
Spades = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King']
Clubs = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King']

poss_suits = [Diamonds, Hearts, Spades, Clubs]
如果
list
为空,则执行
list.remove(card)
会给出一个值错误。您处理了索引器,但没有处理ValueError。

您只需添加:

if suit == Diamonds and Diamonds:
然后,对其他西装也这样做。另一个更好的方法是,如果您使用以下套装:

player_deal = 52
while player_deal > 0:
    try:
        suit = random.choice(poss_suits)
        if suit:
            card = random.choice(suit)
            suit.remove(card)
            Player.hand.append(card)
            player_deal -= 1

这是一个更简单的答案,可以完成这项工作。

只是想:我将实现这个包,以匹配您的实际操作方式。1) 做一副四套的西装。2) 洗牌。3) 将其视为堆栈并从顶部弹出。易于理解,易于编码和测试。它可以在任何需要一副牌的地方使用。注:卡片是[诉讼,价值]的记录。
player_deal = 52
while player_deal > 0:
    try:
        suit = random.choice(poss_suits)
        if suit:
            card = random.choice(suit)
            suit.remove(card)
            Player.hand.append(card)
            player_deal -= 1