Even though it is not considered Pythonic, Python still contains map
and filter
and reduce
can be imported from functools
. Using these functions it is possible to generate the same pipe line as the one you have in scala, albeit it will be written in the opposite direction (from right to left, rather than left to right):
from functools import reduce
a = reduce(lambda f,s: f'{f} .. {s}',
map(lambda nx: f'Result[{nx[0]}]: {nx[1]}',
enumerate(
filter(lambda n: n%20 == 0,
filter(lambda n: len(str(n)) == 2,
filter(lambda n: n <= 170,
map(lambda n: n*4,
range(1,51))))))))
Now, this is lazy, in the sense that it will let each value be transported through the whole pipe before the next is being evaluated. However, since all values are consumed by the final reduce
call, this is not seen.
It is possible to generate a list from each map
or filter
object in each step:
a = reduce(lambda f,s: f'{f} .. {s}',
list(map(lambda nx: f'Result[{nx[0]}]: {nx[1]}',
list(enumerate(
list(filter(lambda n: n%20 == 0,
list(filter(lambda n: len(str(n)) == 2,
list(filter(lambda n: n <= 170,
list(map(lambda n: n*4,
list(range(1,51)))))))))))))))
Both of these expressions, especially the second one, are quite verbose, so I don't know if I would recommend them. I would recommend using list/generator comprehensions and a few intermediate varaiables:
n4 = [n*4 for n in range(1,51)]
fn4 = [n for n in n4 if n <= 170 if len(str(n))==2 if n%20 == 0]
rfn4 = [f'Result[{n}]: {x}' for n, x in enumerate(fn4)]
a = ' .. '.join(rfn4)
Another benefit with this approach (for you, at least) is that with this approach you will keep the order of opeations that is found in scala. It will also, as long as we do list comprehension (as shown) be non-lazy evaluated. If we want lazy evaluation, it is possible to do generator comprehension instead:
n4 = (n*4 for n in range(1,51))
fn4 = (n for n in n4 if n <= 170 if len(str(n))==2 if n%20 == 0)
rfn4 = (f'Result[{n}]: {x}' for n, x in enumerate(fn4))
a = ' .. '.join(rfn4)
Thus, the only difference is that we use parantheses instead of brackets. But, as stated before; since all data is consumed, the difference in this example is rather minimal.