Skip to main content
 首页 » 编程设计

python之检查列表中的索引是否存在

2025年05月04日9kerrycode

我想指出,我使用的是 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 已经挑选的卡片列表。 hand 是我的命令,P4 是 self.cards

中的一张牌

我发现一些解决方案说添加 try block 将解决问题,但我不知道如何在 if 语句中间添加它。

提前致谢!

请您参考如下方法:

list.index() 应该用于查找列表成员的索引。要检查某项是否在列表中,只需使用in:

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