迭代时修改列表 [英] Modifying list while iterating

查看:180
本文介绍了迭代时修改列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

l  = range(100)                         
for i in l:                         
    print i,                         
    print l.pop(0),                  
    print l.pop(0)

上面的python代码给出了与预期完全不同的输出。我想循环遍历项目,以便我可以在循环时跳过项目。

The above python code gives the output quite different from expected. I want to loop over items so that I can skip an item while looping.

请解释。

推荐答案

我曾经被(别人的)聪明代码咬过,试图在迭代时修改列表。我决定在任何情况下都不会这样做。

I've been bitten before by (someone else's) "clever" code that tries to modify a list while iterating over it. I resolved that I would never do it under any circumstance.

您可以使用切片运算符 mylist [:: 3] 跳过列表中的每三个项目。

You can use the slice operator mylist[::3] to skip across to every third item in your list.

mylist = [i for i in range(100)]
for i in mylist[::3]:
  print(i),

关于我的示例的其他要点与 python 3.0 中的新语法有关。

Other points about my example relate to new syntax in python 3.0.


  • 我使用列表推导来定义mylist,因为它适用于Python 3.0(见下文)

  • print是python 3.0中的一个函数


Python 3.0 range()现在表现得像xrange()一样表现,除了它适用于任意大小的值。后者不再存在。

Python 3.0 range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.

这篇关于迭代时修改列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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