可以产生多个连续发电机吗?

时间:2012-05-25 04:01:23

标签: python iterator generator yield

以下是将可迭代项目拆分为子列表的两个函数。我相信这种类型的任务是多次编程的。我使用它们来解析由repr行组成的日志文件,如('result','case',123,4.55)和('dump',..)等等。

我想更改这些,以便它们将产生迭代器而不是列表。因为列表可能会变得非常大,但我可以根据前几个项目决定接受或跳过它。此外,如果iter版本可用,我想嵌套它们,但是这些列表版本会因复制零件而浪费一些内存。

但是从可迭代源派生多个生成器对我来说并不容易,所以我请求帮助。如果可能的话,我希望避免引入新课程。

此外,如果你知道这个问题的更好标题,请告诉我。

谢谢!

def cleave_by_mark (stream, key_fn, end_with_mark=False):
    '''[f f t][t][f f] (true) [f f][t][t f f](false)'''
    buf = []
    for item in stream:
        if key_fn(item):
            if end_with_mark: buf.append(item)
            if buf: yield buf
            buf = []
            if end_with_mark: continue
        buf.append(item)
    if buf: yield buf

def cleave_by_change (stream, key_fn):
    '''[1 1 1][2 2][3][2 2 2 2]'''
    prev = None
    buf = []
    for item in stream:
        iden = key_fn(item)
        if prev is None: prev = iden
        if prev != iden:
            yield buf
            buf = []
            prev = iden
        buf.append(item)
    if buf: yield buf

编辑:我自己的答案

感谢大家的回答,我可以写下我的要求!当然,对于“cleave_for_change”函数,我也可以使用itertools.groupby

def cleave_by_mark (stream, key_fn, end_with_mark=False):
    hand = []
    def gen ():
        key = key_fn(hand[0])
        yield hand.pop(0)
        while 1:
            if end_with_mark and key: break
            hand.append(stream.next())
            key = key_fn(hand[0])
            if (not end_with_mark) and key: break
            yield hand.pop(0)
    while 1:
        # allow StopIteration in the main loop
        if not hand: hand.append(stream.next())
        yield gen()

for cl in cleave_by_mark (iter((1,0,0,1,1,0)), lambda x:x):
    print list(cl),  # start with 1
# -> [1, 0, 0] [1] [1, 0]
for cl in cleave_by_mark (iter((0,1,0,0,1,1,0)), lambda x:x):
    print list(cl),
# -> [0] [1, 0, 0] [1] [1, 0]
for cl in cleave_by_mark (iter((1,0,0,1,1,0)), lambda x:x, True):
    print list(cl),  # end with 1
# -> [1] [0, 0, 1] [1] [0]
for cl in cleave_by_mark (iter((0,1,0,0,1,1,0)), lambda x:x, True):
    print list(cl),
# -> [0, 1] [0, 0, 1] [1] [0]

/

def cleave_by_change (stream, key_fn):
    '''[1 1 1][2 2][3][2 2 2 2]'''
    hand = []
    def gen ():
        headkey = key_fn(hand[0])
        yield hand.pop(0)
        while 1:
            hand.append(stream.next())
            key = key_fn(hand[0])
            if key != headkey: break
            yield hand.pop(0)
    while 1:
        # allow StopIteration in the main loop
        if not hand: hand.append(stream.next())
        yield gen()

for cl in cleave_by_change (iter((1,1,1,2,2,2,3,2)), lambda x:x):
    print list(cl),
# -> [1, 1, 1] [2, 2, 2] [3] [2]

注意:如果有人打算使用这些,请务必在安德鲁指出的每个级别耗尽发电机。因为否则外部生成器产生循环将在内部生成器离开的地方重新开始,而不是在下一个“块”开始的地方重新开始。

stream = itertools.product('abc','1234', 'ABCD')
for a in iters.cleave_by_change(stream, lambda x:x[0]):
    for b in iters.cleave_by_change(a, lambda x:x[1]):
        print b.next()
        for sink in b: pass
    for sink in a: pass

('a', '1', 'A')
('b', '1', 'A')
('c', '1', 'A')

3 个答案:

答案 0 :(得分:8)

亚当的答案很好。这是为了以防万一你好奇如何手工完成:

def cleave_by_change(stream):
    def generator():
        head = stream[0]
        while stream and stream[0] == head:
            yield stream.pop(0)
    while stream:
        yield generator()

for g in cleave_by_change([1,1,1,2,2,3,2,2,2,2]):
    print list(g)

给出:

[1, 1, 1]
[2, 2]
[3]
[2, 2, 2, 2]

(之前的版本需要一个hack,或者在python 3中nonlocal,因为我在stream内分配了generator(),这使{第二个变量也被称为stream本地默认情况下为generator() - 在评论中归功于gnibbler。

请注意,这种方法很危险 - 如果您不“消耗”返回的生成器,那么您将获得越来越多,因为流不会变得更小。

答案 1 :(得分:4)

对于第二个功能,您可以使用itertools.groupby来轻松完成此任务。

这是一个替代实现,现在产生生成器而不是列表:

from itertools import groupby

def cleave_by_change2(stream, key_fn):
    return (group for key, group in groupby(stream, key_fn))

这是它的实际应用(沿途有自由印刷,所以你可以看到发生了什么):

main_gen = cleave_by_change2([1,1,1,2,2,3,2,2,2,2], lambda x: x)

print main_gen

for sub_gen in main_gen:
    print sub_gen
    print list(sub_gen)

哪个收益率:

<generator object <genexpr> at 0x7f17c7727e60>
<itertools._grouper object at 0x7f17c77247d0>
[1, 1, 1]
<itertools._grouper object at 0x7f17c7724850>
[2, 2]
<itertools._grouper object at 0x7f17c77247d0>
[3]
<itertools._grouper object at 0x7f17c7724850>
[2, 2, 2, 2]

答案 2 :(得分:2)

我实施了我所描述的内容:

  

如果您想要的是在返回之前拒绝列表,甚至是   通过为函数提供过滤器参数来构建   可能。当此过滤器拒绝该函数的列表前缀时   抛出当前输出列表并跳过附加到输出列表   直到下一组开始。

def cleave_by_change (stream, key_fn, filter=None):
    '''[1 1 1][2 2][3][2 2 2 2]'''
    S = object()
    skip = False
    prev = S
    buf = []
    for item in stream:
        iden = key_fn(item)
        if prev is S:
           prev = iden
        if prev != iden:
            if not skip:
                yield buf
            buf = []
            prev = iden
            skip = False
        if not skip and filter is not None:
           skip = not filter(item)
        if not skip:
           buf.append(item)
    if buf: yield buf

print list(cleave_by_change([1, 1, 1, 2, 2, 3, 2, 2, 2, 2], lambda a: a, lambda i: i != 2))
# => [[1, 1, 1], [3]]
print list(cleave_by_change([1, 1, 1, 2, 2, 3, 2, 2, 2, 2], lambda a: a, lambda i: i == 2))
# => [[2, 2], [2, 2, 2, 2]]