想象一下,我有一个["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.
我的感觉告诉我,这应该存在于内置,但它正在逃避我。怎么样 你会这样做吗?
答案 0 :(得分:7)
你是说这个?
def head(it):
val = []
for elem in it:
val.append(elem)
yield val
这需要任何可迭代的,而不仅仅是列表。
演示:
>>> for first_elements in head('abcd'):
... print first_elements
...
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
答案 1 :(得分:2)
我可能会这样做:
def head(A) :
for i in xrange(1,len(A)+1) :
yield A[:i]
示例:
for x in head(["a", "b", "c", "d"]) :
print x
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']