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

标签 python

我想指出,我使用的是 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 是我的命令,P4self.cards

中的一张牌

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

提前致谢!

最佳答案

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

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

关于python - 检查列表中的索引是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38339204/

相关文章:

python - Anaconda Jupyter笔记本使用/usr/bin/python3

连续从串口接收可变数据的Python代码

python - 根据回调删除重复项

python - 使用psycopg2动态更改python中的数据库(postgresql)

python - 尝试在 kivy 的速度计上添加动画

python - 如何安装 Python 配方文件 (.py)?

python - Django - 在管理中保存时更新另一个模型

python - 如何通过考虑数据帧列的值的聚合来获取分组

python - 如何检查 python 列表/字典中是否存在第二层(嵌套)键?

python - 来自 Pandas 中两个不同来源的堆叠条形图