当`for`循环列表时,`pop`-元素时发生了什么 [英] What happened when `pop`-ing an element while `for` looping a list

查看:93
本文介绍了当`for`循环列表时,`pop`-元素时发生了什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

arr = [ i for i in xrange(10) ]

for i in arr:
  if i in arr:
    print i
    arr.pop(0)

print arr

输出:

$ python2.7 ts.py 
0
2
4
6
8
[5, 6, 7, 8, 9]

为什么会这样呢?是不是[]?

Why is this the result? Shouldn't it be []?

推荐答案

在迭代时更新序列会产生一些意外结果,这就是为什么从不推荐这样做的原因.下图描述了从列表弹出时每次迭代时变量i的变化方式

Updating a Sequence while Iterating has some unexpected results, which is why it is never recommended. The following graphic depicts how the variable i changes every time you iterate while popping from the list

var    Instruction                    <--------- arr -------------> 
 i                                   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 |     for i in arr                   ^
 |____________________________________|
 |                                    |
 |                                    V
 |     arr.pop(0)                    [1, 2, 3, 4, 5, 6, 7, 8, 9]
 |     
 |     for i in arr                  [1, 2, 3, 4, 5, 6, 7, 8, 9]
 |                                       ^
 |_______________________________________|
 |_______________________________________|
 |                                       |
 |                                       V
 |     arr.pop(0)                    [2, 3, 4, 5, 6, 7, 8, 9]
 |     
 |     for i in arr                  [2, 3, 4, 5, 6, 7, 8, 9]
 |                                          ^
 |__________________________________________|
 |__________________________________________|
 |                                          |
 |                                          V
 |     arr.pop(0)                    [3, 4, 5, 6, 7, 8, 9]
 |     
 |     for i in arr                  [3, 4, 5, 6, 7, 8, 9]
 |                                             ^
 |_____________________________________________|
 |_____________________________________________|
 |                                             |
 |                                             V
 |     arr.pop(0)                    [4, 5, 6, 7, 8, 9] 
 |     
 |     for i in arr                  [4, 5, 6, 7, 8, 9]
 |                                                ^
 |________________________________________________|
 |________________________________________________|
 |                                                |
 |                                                V
 |     arr.pop(0)                    [5, 6, 7, 8, 9] 

这篇关于当`for`循环列表时,`pop`-元素时发生了什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆