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)
我的感觉告诉我,这应该存在于内置,但它正在逃避我.你会怎么做?
你是这个意思?
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)