【问题标题】:Python generator function with predicate带有谓词的 Python 生成器函数
【发布时间】:2016-04-28 03:20:40
【问题描述】:
def group_func(iterable,p):

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

我正在处理 group_func

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

【问题讨论】:

  • 你的hide 函数可以用内置的iter 代替,我想。我假设它的目的是让您处理迭代器,而不是直接处理其他类型的可迭代对象(如序列)。

标签: python iterator generator


【解决方案1】:

你想这样拆分单词吗?

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')])

【讨论】:

  • 你可能想要if result: yield result 在最后,这样你就不会产生一个空列表。
猜你喜欢
  • 2019-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多