V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Zoeeeeecho
V2EX  ›  Python

Python "list index out of range"

  •  
  •   Zoeeeeecho · 2022-09-21 15:07:43 +08:00 · 1485 次点击
    这是一个创建于 554 天前的主题,其中的信息可能已经有所发展或是发生改变。
    苯人刚学 python4 节课,写一个作业 terminal 一直说"IndexError:list index out of range",请大家帮我看看是哪里的问题呢?我还没学会在 V2EX 上发图,劳烦大家戳开链接看看了。第一个链接是我的代码,第二个是报错的图片。麻烦大家了!作业要求是 input 一个数字,然后打出这么多个( 0 ,100 )里的随机数。可以也顺便告诉我一下怎么改么,苯人刚学,真的很笨

    https://imgur.com/3I8XoAT

    https://imgur.com/AanZ5QA
    9 条回复    2022-09-21 15:35:47 +08:00
    zzl22100048
        1
    zzl22100048  
       2022-09-21 15:13:32 +08:00
    number 最长只有 a
    最后 number 取的是第 i 个,肯定有概率报错的
    lonelinsky
        2
    lonelinsky  
       2022-09-21 15:19:22 +08:00
    print 那行中 number[i] 里面 i 是你前面生成的随机数,所以可能会超过 number 里面元素的总个数.

    具体要怎么打印你可以自己思考下
    wliansheng
        3
    wliansheng  
       2022-09-21 15:22:26 +08:00
    因为 `i = random.randint()` 而 number 长度取决于输入的 a ,所以当 i 大于 a 的时候就会 out ,如果你想打印最后一个元素可以用`print(number[-1])`, 直接用`print(number[c])`也会 out ,因为 你是先往 number 里面 append ,然后 c 再加一,这样 c 会等于`len(number)+1`, list 的第一个元素下标是 0 ,也可以使用`print(number[c-1])` 或者把 c+=1 放在 append 前面 用`print(number[c])`
    knva
        4
    knva  
       2022-09-21 15:25:36 +08:00
    打印的时候是否不应该添加[i]
    Zoeeeeecho
        5
    Zoeeeeecho  
    OP
       2022-09-21 15:28:29 +08:00
    @zzl22100048 天!对咯!谢谢!
    RRRoger
        6
    RRRoger  
       2022-09-21 15:29:43 +08:00
    每个人都有刚开始的时候 加油
    keepeye
        7
    keepeye  
       2022-09-21 15:31:12 +08:00
    变量 i 是什么 number[i] 意义是什么
    gablic
        8
    gablic  
       2022-09-21 15:32:55 +08:00
    number 是一个 list ,number[i]是对他进行切片,你可以去搜下切片的语法,然后思考下为什么报错。
    ncepuzs
        9
    ncepuzs  
       2022-09-21 15:35:47 +08:00
    我想你最后 print 语句原本想要做的应该是将数组中的元素全部打印出来吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5730 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 01:51 · PVG 09:51 · LAX 18:51 · JFK 21:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.