当`for`循环列表时,`pop`

编程入门 行业动态 更新时间:2024-10-27 19:21:19
本文介绍了当`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`

本文发布于:2023-11-06 16:20:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564198.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   pop

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!