首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python 3:列表索引超出范围

Python 3:列表索引超出范围
EN

Stack Overflow用户
提问于 2015-07-24 05:04:46
回答 3查看 146关注 0票数 1

每次运行这个命令时,我都会遇到这样的错误:IndexError:list index out of range。

代码语言:javascript
复制
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])
EN

回答 3

Stack Overflow用户

发布于 2015-07-24 05:08:12

按该索引删除前打印cards[cardIndex]

代码语言:javascript
复制
while cards: # Because we need to stop somewhere
    cardIndex = random.randint(0, randomness)
    print(cards[cardIndex])
    del cards[cardIndex]
    randomness = randomness -1

而且你根本不需要randomness

代码语言:javascript
复制
while cards:
    cardIndex = random.randrange(len(cards))
    print(cards[cardIndex])
    del cards[cardIndex]

您可以使用以下两种random.sample之一来完成此操作

代码语言:javascript
复制
for c in random.sample(cards, len(cards)):
    print(c)

random.shuffle (将修改cards列表):

代码语言:javascript
复制
random.shuffle(cards)
for c in cards:
    print(c)
票数 3
EN

Stack Overflow用户

发布于 2015-07-24 05:29:38

您的问题是您首先删除卡片,然后打印它,所以问题是当您选择最后一张卡片时:

代码语言:javascript
复制
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

您想要的是更改打印和删除:

代码语言:javascript
复制
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 -1

len()告诉你有多少东西在列表中,它现在应该工作了:)

票数 2
EN

Stack Overflow用户

发布于 2015-07-24 05:11:39

代码语言:javascript
复制
while cards:
    idx = random.randint(0, len(cards) - 1)
    print(cards[idx])
    del cards[idx]
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31598022

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档