【问题标题】:A len(list) gives TypeError: object of type 'NoneType' has no len()一个 len(list) 给出 TypeError: 'NoneType' 类型的对象没有 len()
【发布时间】:2021-03-27 16:28:15
【问题描述】:

我正在尝试制作一副纸牌,而不是取出 2 x 2 并返回结果。 我想避免“超出索引”错误。 但我不断收到“typeError:'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 

我真的不知道牌组列表在哪里变成了 Nonetype 对象。 感谢您的帮助。

【问题讨论】:

  • deck = deck.remove(card) - list.remove 返回None,它在列表中就地执行

标签: python list nonetype


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你出错的地方是 card_dealer 方法的第一个 if 语句。 当您从列表中删除卡时,您必须这样做:

    deck.remove(card)  # removing the element
    

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

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

    从列表中删除时,只需按照我提到的第一种方法即可。

    【讨论】:

      猜你喜欢
      • 2021-03-03
      • 2015-07-30
      • 1970-01-01
      • 2018-08-14
      • 2016-06-06
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 2018-06-11
      相关资源
      最近更新 更多