Python:从循环迭代器的内部和外部移除项目 [英] Python: removing items from inner and outer for loop iterators

查看:151
本文介绍了Python:从循环迭代器的内部和外部移除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码有潜在危险吗?它会干扰内部和外部迭代?

  for a listA:
for b in listB:
if [... something ...]:
...其他...
listA.remove(a)
listB.remove(b)
break


解决方案

这段代码有潜在危险吗?依靠。

考虑这个例子

  listA = [1,2,3,4] 

>>> for a listA:
listA.remove(a)
打印一个

因为在删除物品时,所有物品都被推向左边,假设你要迭代的物品会自动移动到下一个元素。

迭代:

  listA = [1,2,3,4] 
^
|
_____________ |

listA.remove(a)


listA = [2,3,4]
^
|
_____________ |


打印a
(输出)1

第二次迭代:

  listA = [2,3,4] 
^
|
_______________ |

listA.remove(a)

listA = [2,4]
^
|
_______________ |


打印a
(输出)3

第三次迭代:

  listA = [2,4] 
^
|
_________________ |

(退出循环)


Is this piece of code potentially dangerous? Will it mess up with the inner and outer iterations?

for a in listA:
            for b in listB: 
                if [... something...]:
                    ... something else...
                    listA.remove(a)
                    listB.remove(b)
                    break

解决方案

Is this piece of code potentially dangerous? Depends. Reducing the size of a sequence while iterating over it would give unexpected behavior.

Consider this Example

listA = [1,2,3,4]

>>> for a in listA:
    listA.remove(a)
    print a

Because, on removing the items, all the items beyond it, are pushed towards the left, the item that you are supposing to iterate would automatically move to the next element

First Iteration:

    listA = [1,2,3,4]
             ^
             |
_____________|

    listA.remove(a)


    listA = [2,3,4]
             ^
             |
_____________|


    print a
    (outputs) 1

Second Iteration:

    listA = [2,3,4]
               ^
               |
_______________|

    listA.remove(a)

    listA = [2,4]
               ^
               |
_______________|


    print a
    (outputs) 3

Third Iteration:

    listA = [2,4]
                 ^
                 |
_________________|

(Exits the Loop)

这篇关于Python:从循环迭代器的内部和外部移除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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