Python idiom for iterating over changing list

前端 未结 4 1507
死守一世寂寞
死守一世寂寞 2021-01-21 09:41

Is there a better (more obvious/idiomatic) way in python to write an equivalent of

index = 0
while index < len(some_list):
    do_some_stuff(some_list[index])         


        
4条回答
  •  清歌不尽
    2021-01-21 10:13

    If order doesn't matter, you can enumerate backwards so that deletes don't mess up the part of the list you haven't processed yet.

    for i, item in enumerate(reversed(somelist), -len(somelist)+1):
        do_some_stuff(item)
        if delete_element(item):
            del somelist[-i]
    

    If order does matter, reverse the list, do this trick then reverse it again. That'll confuse 'em!

    Depending on the situation, you could replace the item with a marker like None. Either strip it out later or have other places this list is used chack None.

    for i, item in enumerate(somelist)):
        do_some_stuff(item)
        if delete_element(item):
            somelist[i] = None
    
    somelist = [item for item in somelist if item]
    

提交回复
热议问题