len(列表)给出了TypeError:类型为“NoneType”的对象没有len()

2024-05-23 20:02:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着制作一副牌,然后取出2 x 2并返回结果。 我希望避免“索引外”错误。 但我一直在讨论“typeError:objectoftype'NoneType'没有len()”错误。 正如我在这里检查的,它主要来自函数用法,原因是命令查询原则, 但我不认为这会发生在这里

***代码***


    def deck_creator():
        suits = ("Hearts", "Diamonds", "Clubs", "Spades")
        values = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
        deck = []
    
        for suit in suits:
            for value in values:
                card = value + " of "+ suit
                deck.append(card)
    
        return deck
    
    def card_dealer(deck):
        """
        5. Deal two cards to the Dealer and two cards to the Player
        """
        print(type(deck))   # ==> !!! <class 'list'> !!! 
        print(len(deck))    # ==> !!! 52 !!! 
        dealers_cards = []
        players_cards = []
        shorter_then_two = True
        while shorter_then_two == True:
            if len(dealers_cards) < 2 or len(players_cards) < 2 :
                card_number = random.randint(1, (len(deck) + 1))   # typeError: object of type 'NoneType' has no len()
                card = deck[card_number]
                if len(dealers_cards) < 2:
                    dealers_cards.append(card)
                else:
                    players_cards.append(card)
                deck = deck.remove(card)
            else:
                shorter_then_two = False
        return players_cards, dealers_cards
    
    a = deck_creator()
    # print(a)
    b = card_dealer(a)
    # print(b)

结果:

card_number = random.randint(1, (len(deck) + 1))   
TypeError: object of type 'NoneType' has no len()
<class 'list'>
52 

我真的搞不清楚甲板列表在哪里变成了非类型对象。 谢谢你的帮助


Tags: ofnumberlentypecardcardsprintshorter
2条回答

在第一个if卡商方法声明中,您将出现错误。 从列表中删除卡时,必须执行以下操作:

deck.remove(card)  # removing the element

您的操作方式将重新分配列表。 remove()不返回任何值(不返回任何值)

deck = deck.remove(card) # will make the list empty (None).

从列表中删除时,只需遵循我提到的第一种方法

这是因为您正在将值赋回deck变量,但list.remove(index)返回None,而不是更改列表

>>> l = [1, 2, 3]
>>> l.remove(1)  # None!
>>> l
[2, 3]

相关问题 更多 >