2
# currently I have this code

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

I was wondering if there was a way to squash it into one line

# looking for something like

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

2 Answers 2

4

You can use map. The map accepts two parameters: a function and an iterable. It iterates the iterable and apply the function and returns an iterator (which yields mapped values - function(first item), function(seoncd item), ...)

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

yield from here is not necessary, because the map returns an iterator (in Python 3.x):

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

Example:

>>> 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']
Sign up to request clarification or add additional context in comments.

Comments

3

For something simple and short you can return a generator expression which basically is the same as yield,

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.