how to correctly modify the iterator of a loop in python from within the loop

后端 未结 4 1573
清酒与你
清酒与你 2021-02-08 11:37

what I basically need is to check every element of a list and if some criteria fit I want to remove it from the list.

So for example let\'s say that

list         


        
4条回答
  •  死守一世寂寞
    2021-02-08 12:18

    Its better not to reinvent things which are already available. Use filter functions and lambda in these cases. Its more pythonic and looks cleaner.

    filter(lambda x:x not in ['b','c'],['a','b','c','d','e'])
    

    alternatively you can use list comprehension

    [x for x in ['a','b','c','d','e'] if x not in ['b','c']]
    

提交回复
热议问题