All but the last N elements of iterator in Python

前端 未结 6 1584
情书的邮戳
情书的邮戳 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:00

    Based on Ignacio Vazquez-Abrams's description:

    from collections import deque
    
    def all_but_the_last_n(iterable, count):
        q = deque()
        i = iter(iterable)
        for n in range(count):
            q.append(i.next())
        for item in i:
            q.append(item)
            yield q.popleft()
    

    I wondered whether it was better to use the deque right to left (append, popleft) or left to right (appendleft, pop). So i timed it with python 2.5.2 and found that rtl was 3.59 usec while ltr was 3.53 usec. The difference of 0.06 usec is not significant. the test was to append a single item and pop a single item.

提交回复
热议问题