Python: Adding element to list while iterating

前端 未结 11 650
太阳男子
太阳男子 2020-12-02 15:37

I know that it is not allowed to remove elements while iterating a list, but is it allowed to add elements to a python list while iterating. Here is an example:



        
11条回答
  •  佛祖请我去吃肉
    2020-12-02 15:55

    Expanding S.Lott's answer so that new items are processed as well:

    todo = myarr
    done = []
    while todo:
        added = []
        for a in todo:
            if somecond(a):
                added.append(newObj())
        done.extend(todo)
        todo = added
    

    The final list is in done.

提交回复
热议问题