How not to miss the next element after itertools.takewhile()

后端 未结 2 1703
醉酒成梦
醉酒成梦 2020-12-15 06:18

Say we wish to process an iterator and want to handle it by chunks.
The logic per chunk depends on previously-calculated chunks, so groupby() does not help.

2条回答
  •  萌比男神i
    2020-12-15 06:41

    Given the callable GetNewChunkLogic() will report True along first chunk and False afterward.
    The following snippet

    1. solves the 'additional next step' problem of takewhile .
    2. is elegant because you don't have to implement the back-one-step logic .

    def partition(pred, iterable):
        'Use a predicate to partition entries into true entries and false entries'
        # partition(is_odd, range(10)) -->  1 3 5 7 9 and 0 2 4 6 8
        t1, t2 = tee(iterable)
        return filter(pred, t1), filterfalse(pred, t2)
    
    while True:
        head, tail = partition(GetNewChunkLogic(), myIterator)
        process(head)
        myIterator = tail
    

    However, the most elegant way is to modify your GetNewChunkLogic into a generator and remove the while loop.

提交回复
热议问题