![](/img/trans.png)
[英]How to remove characters from a string after a certain point within a list?
[英]How to remove certain int from list within a list?
我正在嘗試將二十一點游戲作為初學者項目。 當我嘗試從牌組中取出正在處理的牌時,我得到這個: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 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()
嵌套列表表現為列表列表。 這意味着您必須指定第一個列表的索引才能訪問嵌套列表中的項目。
new_deck = deck[foo].remove(card)
這進入列表 [foo],例如讓 foo = 1。列表將是 [3,3,3,3]。
card 是一個 int not list。這就是你收到這個錯誤的原因。 您的套牌包含列表列表。 如果要刪除單個 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.