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

后端 未结 4 1579
清酒与你
清酒与你 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:37

    This is exactly what itertools.ifilter is designed for.

    from itertools import ifilter
    
    ifilter(lambda x: x not in ['b', 'c'], ['a', 'b', 'c', 'd', 'e'])
    

    will give you back a generator for your list. If you actually need a list, you can create it using one of the standard techniques for converting a generator to a list:

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

    or

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

提交回复
热议问题