每次运行这个命令时,我都会遇到这样的错误:IndexError:list index out of range。
import random
cards = ['2', '2', '2', '2', '3', '3', '3', '3', '4', '4', '4', '4', '5', '5', '5', '5', '6', '6', '6', '6', '7', '7', '7', '7', '8', '8', '8', '8', '9', '9', '9', '9', '10', ',10', '10', '10', 'J', 'J', 'J', 'J', 'Q', 'Q', 'Q', 'Q', 'K', 'K', 'K', 'K', 'A', 'A', 'A', 'A']
randomness = 51
while True:
cardIndex = random.randint(0, randomness)
del cards[cardIndex]
randomness = randomness -1
print(cards[cardIndex])发布于 2015-07-24 05:08:12
按该索引删除前打印cards[cardIndex]:
while cards: # Because we need to stop somewhere
cardIndex = random.randint(0, randomness)
print(cards[cardIndex])
del cards[cardIndex]
randomness = randomness -1而且你根本不需要randomness:
while cards:
cardIndex = random.randrange(len(cards))
print(cards[cardIndex])
del cards[cardIndex]您可以使用以下两种random.sample之一来完成此操作
for c in random.sample(cards, len(cards)):
print(c)或random.shuffle (将修改cards列表):
random.shuffle(cards)
for c in cards:
print(c)发布于 2015-07-24 05:29:38
您的问题是您首先删除卡片,然后打印它,所以问题是当您选择最后一张卡片时:
randomness = 51
while True:
cardIndex = random.randint(0, randomness) #random.randint(0, 51) could give num 51 so card 52
del cards[cardIndex] # deleted 52nd card (num 51)
randomness = randomness -1
print(cards[cardIndex]) # there is no 52nd card (num 51) anymore您想要的是更改打印和删除:
while len(cards) > 0: # once yours pack of card is empty you want to stop
cardIndex = random.randint(0, randomness)
print(cards[cardIndex])
del cards[cardIndex]
randomness = randomness -1len()告诉你有多少东西在列表中,它现在应该工作了:)
发布于 2015-07-24 05:11:39
while cards:
idx = random.randint(0, len(cards) - 1)
print(cards[idx])
del cards[idx]https://stackoverflow.com/questions/31598022
复制相似问题