具有谓词的Python生成器函数

时间:2016-04-28 03:20:41

标签: python iterator generator

def group_func(iterable,p):

    for i in iterable:
         yield [i]
         if p(i):
             yield i

我正在使用group_func

但是,我上面定义的group_func无法做到这一点......显然。有什么帮助吗?

1 个答案:

答案 0 :(得分:4)

你想要像这样拆分?

def hide(iterable):
    for v in iterable:
        yield v

def group_func(iterable,p):
    result = []
    for i in iterable:
         result.append(i)
         if p(i):
             yield result
             result = []
    yield result


print([v for v in group_func('combustibles', lambda x : x in 'aeiou')])
print([v for v in group_func(hide('combustibles'), lambda x : x in 'aeiou')])