Python idiom for iterating over changing list

前端 未结 4 1504
死守一世寂寞
死守一世寂寞 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:35

    You might break up the operations into two separate loops, and use a list comprehension for the second part.

    for value in some_list:
        do_some_stuff(value)
    
    some_list = [value for value in some_list if not delete_element(value)]
    

    Another solution would be to iterate over a copy of the list, and use enumerate to keep track of the indices without having to maintain a counter by hand.

    for index, value in enumerate(some_list[::-1]):
        do_some_stuff(value)
        if delete_element(value):
            del some_list[-index - 1]
    

    You'd want to iterate backwards so you don't have to adjust index for the deleted elements.

提交回复
热议问题