为 python 中 "yield from" 的对象应用函数

Apply function for objects from "yield from" in python

# currently I have

def some_func():
    for match in re.finditer(regex, string):
        yield other_func(match)

我想知道是否有一种方法可以在语法上将其压缩成一行

# looking for something like

def some_func():
    yield from other_func(re.finditer(regex, string))

您可以使用 mapmap 接受两个参数:一个函数和一个可迭代对象。它迭代可迭代对象并应用函数和 returns 迭代器(产生映射值 - 函数(第一项),函数(第二项),...)

def some_func():
    yield from map(other_func, re.finditer(regex, string))

yield from这里是没有必要的,因为mapreturns一个迭代器(在Python3.x):

def some_func():
    return map(other_func, re.finditer(regex, string))

示例:

>>> import re
>>>
>>> def other_func(match):
...     return match.group()
...
>>> def some_func():
...     return map(other_func, re.finditer(regex, string))
...
>>> regex = '.'
>>> string = 'abc'
>>> list(some_func())
['a', 'b', 'c']

对于简单而简短的事情,你可以return一个基本上与 yield 相同的生成器表达式,

def some_func():
    return (other_func(match) for match in re.finditer(regex, string))