在Python中迭代列表头的优雅方式

Jul*_*lik 2 python iteration list generator

想象一下,我有一份清单 ["a", "b", "c", "d"]

我正在寻找一个Pythonic习惯用于大致这样做:

for first_elements in head(mylist):
   # would first yield ["a"], then ["a", "b], then ["a", "b", "c"]
   # until the whole list gets generated as a result, after which the generator
   # terminates.
Run Code Online (Sandbox Code Playgroud)

我的感觉告诉我,这应该存在于内置,但它正在逃避我.你会怎么做?

Mar*_*ers 7

你是这个意思?

def head(it):
    val = []
    for elem in it:
        val.append(elem)
        yield val
Run Code Online (Sandbox Code Playgroud)

这需要任何可迭代的,而不仅仅是列表.

演示:

>>> for first_elements in head('abcd'):
...     print first_elements
... 
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
Run Code Online (Sandbox Code Playgroud)

  • 你真的需要`iter`吗?难道你不能只使用一个简单的`for`循环(而不是`while`)? (2认同)
  • @Julik:考虑到该版本需要一个序列,我也接受任何可迭代(包括生成器). (2认同)