简体   繁体   English

如何从列表中的列表中删除某些整数?

[英]How to remove certain int from list within a list?

I'm trying to make a blackjack game as a beginners project.我正在尝试将二十一点游戏作为初学者项目。 When I try to remove the card that's being dealt from the deck I get this: ValueError: list.remove(x): x not in the list.当我尝试从牌组中取出正在处理的牌时,我得到这个:ValueError: list.remove(x): x not in the list。 How can I fix this?我怎样才能解决这个问题?

This is my code:这是我的代码:

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 which suit from the number should be the card
    new_deck = deck.remove(card) # Here is the problem
    print(new_deck)
    print(card)

deal_cards()

nested lists behave as lists of lists.嵌套列表表现为列表列表。 That meaning you would have to specify an index of the first list to get access to the items in the nested list.这意味着您必须指定第一个列表的索引才能访问嵌套列表中的项目。

 new_deck = deck[foo].remove(card)

this goes into list[foo], for example let foo = 1. The list would be [3,3,3,3].这进入列表 [foo],例如让 foo = 1。列表将是 [3,3,3,3]。

card is an int not list.That's why you are getting this error. card 是一个 int not list。这就是你收到这个错误的原因。 Your deck contains list of lists.您的套牌包含列表列表。 If you want to remove a single int then you should specify which list it should be removed.如果要删除单个 int,则应指定应删除的列表。 You should change your code as following:你应该改变你的代码如下:

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM