Python 检查列表中是否存在索引
我想指出的是,我使用的是Discord.py,其中一些包含libs 因此,我试图检查列表中是否存在索引,但我不断得到Python 检查列表中是否存在索引,python,Python,我想指出的是,我使用的是Discord.py,其中一些包含libs 因此,我试图检查列表中是否存在索引,但我不断得到ValueError表示该索引在我的列表中不存在 这是我的密码: def deal_card(self): U = self.usedCards randCard = randchoice(list(self.cards)) if not U: #check if it is empty #if it is e
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
我发现了一些解决方案,即添加<代码>尝试< /Cord>块将解决这个问题,但是我不知道如何在IF语句的中间添加它。 提前谢谢
list.index()
应用于查找列表成员的索引。要检查项目是否在列表中,只需使用中的:
if not U:
# do stuff
elif randCard in U:
# do other stuff
list.index()
应用于查找列表成员的索引。要检查项目是否在列表中,只需使用中的:
if not U:
# do stuff
elif randCard in U:
# do other stuff
您不需要使用索引函数:
elif randCard in U:
您不需要使用索引功能:
elif randCard in U:
这可能是一种糟糕的发牌方式,因为这样你的牌堆和牌组中都有牌
为什么不把牌四处移动呢
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()
这可能是一种糟糕的发牌方式,因为这样你的牌堆和牌组中都有牌
为什么不把牌四处移动呢
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()
如果出于某种原因仍想使用.index
功能,而不遵循上述建议,则可以使用try
语句,如下所示:
try:
c = U.index(randCard)
randCard = randchoice(list(self.cards))
U.append(randCard)
except ValueError:
U.append(randCard)
如果出于某种原因仍想使用.index
功能,而不遵循上述建议,则可以使用try
语句,如下所示:
try:
c = U.index(randCard)
randCard = randchoice(list(self.cards))
U.append(randCard)
except ValueError:
U.append(randCard)
哦,我不知道。非常感谢你!哦,我不知道。非常感谢你!只是一个不能回答你的问题的注释——如果你每次发牌时都从牌组中移除所选的牌,那么你的代码就会简单得多<代码>self.shuffle=random.shuffle(self.cards);return self.shuffle.pop()<代码>self.shuffle=random.shuffle(self.cards);return self.shuffle.pop()