Python:在循环中移除循环体要素

改造之前一个数据处理代码,需要在循环中根据判断条件来决定是否移除当前的循环体对象。

简单示例代码:

>>> lst = [1, 2, 3, 4, 5, 6, 7, 8]
>>> for x in lst:
        if x < 6: lst.remove(x) 
>>> lst
[2, 4, 6, 7, 8]

这个示例中返回结果有错误,即本意是要移除x<6的对象,但最终并没有完全移除,造成了隔一个移除的结果。造成错误结果的主要原因是循环体在循环过程中并不知道循环体发生了变化,导致循环体在定位到下一个循环体对象时发生了位移。其解决方案也比较简单:

1、拷贝一个循环体,使用拷贝后的循环体进行循环,而修改则在原来的循环体,这样就互不影响。

2、对循环体使用reversed()函数,即:

>>> lst = [1, 2, 3, 4, 5, 6, 7, 8]
>>> for x in reversed(lst):
        if x < 6: lst.remove(x) 
>>> lst
[6, 7, 8]

 

参考:

https://sopython.com/canon/95/removing-items-from-a-list-while-iterating-over-the-list/

 


已发布

分类

来自

标签:

评论

《 “Python:在循环中移除循环体要素” 》 有 12 条评论

  1. medicament kamagra en france pharmacie

    acheter kamagra en ligne obtenir une prescription

  2. purchase enclomiphene generic order

    buying enclomiphene ireland over the counter

  3. buying androxal usa where to buy

    cheapest buy androxal generic a canada

  4. how to order flexeril cyclobenzaprine generic a canada

    ordering flexeril cyclobenzaprine uk order

  5. buy dutasteride generic side effect

    cheap dutasteride generic best price

  6. Buy gabapentin without a perscription or membership

    online order gabapentin generic switzerland

  7. fildena without rx

    purchase fildena buy in london

  8. how to order itraconazole generic dosage

    discount itraconazole buy online canada

  9. purchase staxyn usa pharmacy

    buying staxyn without a script

  10. buying avodart generic information

    discount avodart generic in canada

  11. online order rifaximin usa overnight delivery

    cheap rifaximin price netherlands

  12. kamagra žádný lékař

    kamagra bez pナ册dpisu kanadskテゥho lテゥkaナ册

回复 discount staxyn canada low cost 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注