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
xcc7624
V2EX  ›  Python

python 初学者又提问了

  •  
  •   xcc7624 · 2014-07-17 18:01:10 +08:00 · 2911 次点击
    这是一个创建于 3577 天前的主题,其中的信息可能已经有所发展或是发生改变。
    lst = range(10)

    for item in lst:
    lst.pop(0)
    print item
    print lst
    #结果
    0
    0
    1
    2
    2
    4
    3
    6
    4
    8
    [5, 6, 7, 8, 9]
    为什么会是这样
    9 条回复
    O21
        1
    O21  
       2014-07-17 18:04:19 +08:00
    for i in range(10):
    print i

    这样写比较简单吧。。
    puyo
        2
    puyo  
       2014-07-17 18:13:09 +08:00
    list.pop([i])
    Remove the item at the given position in the list, and return it.



    懂了嘛。
    xcc7624
        3
    xcc7624  
    OP
       2014-07-17 19:37:27 +08:00 via Android
    @puyo为什么只迭代了五次?
    puyo
        4
    puyo  
       2014-07-17 19:46:24 +08:00   ❤️ 1
    @xcc7624 因为进入如循环后要去取lst中对应item的下标。
    第一次取第0个,得到的是0
    第二次取第1个,这时候就是从pop之后的列表去取了,是2
    ...
    第五次得到的就是8,这时候lst表中只有5个数字里。
    在第六次的时候,越界了。
    xcc7624
        5
    xcc7624  
    OP
       2014-07-17 19:55:19 +08:00 via Android
    @puyo越界了为什么没抛出异常
    kqz901002
        6
    kqz901002  
       2014-07-17 20:00:02 +08:00
    @puyo 这样写code有没有实际意义?或者这样写貌似会出现误解啊
    kqz901002
        7
    kqz901002  
       2014-07-17 20:01:27 +08:00
    @xcc7624 他说的越界的意思是 目前lst只有五个元素,五次循环结束了,就应该结束循环
    puyo
        8
    puyo  
       2014-07-17 21:23:55 +08:00
    @kqz901002 没什么意义吧,就算要间隔取数加step就好了。这样写也比较难以理解。
    vellow
        9
    vellow  
       2014-07-17 23:17:00 +08:00
    是不是这样,for循环的index+1不会每次都去查询lst具体有多长,只有遇到终点就结束,所以旧的index会应用到新的lst上?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   955 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:33 · PVG 07:33 · LAX 16:33 · JFK 19:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.