2016-07-12 51 views
1

我想說明的是,我正在使用Discord.py以及它包含的一些庫。檢查列表中是否存在索引

所以我試圖檢查一個列表中的索引是否存在,但我不斷收到ValueError說這個索引不存在於我的列表中。

這裏是我的代碼:

def deal_card(self): 
     U = self.usedCards 
     randCard = randchoice(list(self.cards)) 
     if not U: #check if it is empty 
      #if it is empty, just add the card to used cards 
      U.append(randCard) 
     elif U.index(randCard): #check if card is already in the list 
      #if it is, pick another one 
      randCard = randchoice(list(self.cards)) 
      U.append(randCard) 
     else: #check if card is not in list 
      #if it is not, just add it to the used cards 
      U.append(randCard) 
     return randCard 

self.cards充滿了卡的名字和self.usedCards是randCard alredy挑選的卡的列表。 hand是我的命令,並P4self.cards

我找到了一些解決方案,說加入try塊就能解決問題的卡之一,但我不知道如何將其添加到我的if語句的中間。

在此先感謝!

+1

剛一說明,不回答你問題 - 如果您每次處理一張卡時只是從卡組中移除選定的卡,它會使您的代碼變得更加簡單。 'self.shuffle = random.shuffle(self.cards);返回self.shuffle.pop()' –

+0

謝謝@PaulBecotte,我會檢查你的建議:') –

回答

4

list.index()應該用於查找列表成員的索引。要檢查項目是否在列表,只需使用in

if not U: 
    # do stuff 
elif randCard in U: 
    # do other stuff 
+0

哦,不知道。非常感謝你! –

1

你不需要使用索引功能:

elif randCard in U:

+0

謝謝師父,我不知道! –

2

這可能是一個可怕的方式來處理你的卡片,因爲你的卡片裏有你的卡片

爲什麼不移動卡片?

import random 

cards = ['H{}'.format(val) for val in range(1, 11)] 
print(cards) 
discard_pile = [] 

while cards: 
    random.shuffle(cards) 
    card = cards.pop() 
    print('You drew a {}'.format(card)) 
    discard_pile.append(card) 

while discard_pile: 
    cards.append(discard_pile.pop()) 

# or 

cards.extend(discard_pile) 
discard_pile.clear() 
+0

我會試試這個方法,謝謝:') –

1

如果您仍想使用.index功能出於某種原因,並沒有按照上述建議你可以使用try聲明如下:

try: 
    c = U.index(randCard) 
    randCard = randchoice(list(self.cards)) 
    U.append(randCard) 
except ValueError: 
    U.append(randCard)