gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:17:13 33 4
gpt4 key购买 nike

我想指出,我使用的是 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com