【问题标题】:How to remove certain int from list within a list?如何从列表中的列表中删除某些 int?
【发布时间】:2019-12-29 11:02:57
【问题描述】:

我正在尝试将二十一点游戏作为初学者项目。当我尝试从牌组中取出正在处理的牌时,我得到这个: ValueError: list.remove(x): x not in the list。我该如何解决这个问题?

这是我的代码:

import random

deck = [[2, 2, 2, 2],
        [3, 3, 3, 3],
        [4, 4, 4, 4],
        [5, 5, 5, 5],
        [6, 6, 6, 6],
        [7, 7, 7, 7],
        [8, 8, 8, 8],
        [9, 9, 9, 9],
        [10, 10, 10, 10],
        [10, 10, 10, 10],
        [10, 10, 10, 10],
        [10, 10, 10, 10],
        [11, 11, 11, 11]
        ]

def deal_cards():
    number = random.choice(deck[0:][0:]) # selecting the number of the card
    card = random.choice(number) # selecting wich suit from the number sould be the card
    new_deck = deck.remove(card) # Here is the problem
    print(new_deck)
    print(card)

deal_cards()

【问题讨论】:

    标签: python list function random blackjack


    【解决方案1】:

    card 是一个 int 非列表。这就是您收到此错误的原因。您的套牌包含列表列表。如果要删除单个 int,则应指定应删除的列表。 你应该改变你的代码如下:

    def deal_cards():
        number = random.choice(deck[0:][0:])# selecting the number of the card
        card = random.choice(number)# selecting wich suit from the number
        deck[deck.index(number)].remove(card) # problem fixed
        print(deck) # remove returns nothing
        print(card)
    

    【讨论】:

      【解决方案2】:

      嵌套列表表现为列表列表。这意味着您必须指定第一个列表的索引才能访问嵌套列表中的项目。

      new_deck = deck[foo].remove(card)
      
      

      这进入列表[foo],例如让foo = 1。列表将是[3,3,3,3]。

      【讨论】:

        猜你喜欢
        • 2018-09-04
        • 2016-03-12
        • 1970-01-01
        • 2019-01-07
        • 1970-01-01
        • 2013-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多