All but the last N elements of iterator in Python

前端 未结 6 1563
情书的邮戳
情书的邮戳 2021-01-02 21:10

What is the best way to get all but the last N elements of an iterator in Python? Here is an example of it in theoretical action:

>>> list(all_but_         


        
6条回答
  •  温柔的废话
    2021-01-02 22:07

    This is compact (aside from consume recipe taken from itertools recipes) and should run at C speed:

    import collections
    import operator
    from itertools import islice, tee
    
    
    def truncate(iterable, n):
        a, b = tee(iterable)
        consume(b, n)
        return map(operator.itemgetter(0), zip(a, b))
    
    
    # From itertools recipes
    def consume(iterator, n=None):
        "Advance the iterator n-steps ahead. If n is None, consume entirely."
        # Use functions that consume iterators at C speed.
        if n is None:
            # feed the entire iterator into a zero-length deque
            collections.deque(iterator, maxlen=0)
        else:
            # advance to the empty slice starting at position n
            next(islice(iterator, n, n), None)
    

提交回复
热议问题