Alexandr
Alexandr

Reputation: 48

How to convert this loop into list comprehension?

Hello i would like make list comprehension for two loops and return value from first loop. I have example:

rows = []
for row in value:
    for pattern, sub_pattern in zip(pattern_tag, sub_pattern_list):
        row = re.sub(pattern, sub_pattern, row)
    rows.append(row)

how do I make a list, through list Comprehension, so that it gives the same result

Upvotes: 0

Views: 166

Answers (2)

Nikolaj Š.
Nikolaj Š.

Reputation: 1986

To elaborate on Ricardo Bucco's answer and luk2302's comment.

List comprehensions create lists from other lists/iterables. Every item of "source" iterable either produces one item of resulting list or is skipped (if list comprehension has if clause). The order is preserved.

So your outer for loop can be converted to a list comprehension, since it constructs a list of replacements from a list of strings (presumably).

rows = [re.sub(..., ..., row) for row in value]

Inner for loop creates no list, and instead does a lot of subsequent replacements on a string, so it's not something that could be done using list comprehensions (hence _Riccardo_s' idea to use reduce()).

Upvotes: 0

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

This is probably not what you were looking for, but it's still a one-liner that makes use of the functools.reduce function:

from functools import reduce
from re import sub

rows = [
    reduce(
        lambda prev, curr: sub(*curr, prev),
        zip(pattern_tag, sub_pattern_list),
        row,
    )
    for row in value
]

Upvotes: 1

Related Questions