# 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))
# 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))
您可以使用map
. 接受两个参数:map
一个函数和一个可迭代对象。它迭代可迭代并应用函数并返回一个迭代器(它产生映射值 - 函数(第一项),函数(seoncd项),...)
def some_func():
yield from map(other_func, re.finditer(regex, string))
yield from
这里没有必要,因为map
返回一个迭代器(在 Python 3.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']
对于一些简单而简短的事情,您可以返回一个与 yield 基本相同的生成器表达式,
def some_func():
return (other_func(match) for match in re.finditer(regex, string))