All but the last N elements of iterator in Python

前端 未结 6 1580
情书的邮戳
情书的邮戳 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 21:49

    Use a collections.deque. Push N items from the source on the first invocation. On each subsequent invocation, pop an item out, push an item in from the source, and yield the popped item.

提交回复
热议问题