本文介绍了当`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`
发布评论