Is there any possible way to achieve a non-lazy left to right invocation of operations on a list in python ?
e.g. scala
val a = ((1 to 50)
.map(_ * 4)
.filter( _ <= 170)
.filter(_.toString.length == 2)
.filter (_ % 20 == 0)
.zipWithIndex
.map{ case(x,n) => s"Result[$n]=$x"}
.mkString(" .. "))
a: String = Result[0]=20 .. Result[1]=40 .. Result[2]=60 .. Result[3]=80
While I realize many folks will not prefer the above syntax, I like the ability to move left to right and add arbitrary operations as we go.
The python for comprehension is imo not easy to read when there are three or more operations. The result seems to be we're required to break everything up into chunks.
[f(a) for a in g(b) for b in h(c) for ..]
Is there any chance for the approach mentioned?
Note: I tried out a few libraries including toolz.functoolz. That one is complicated by python3 lazy evaluation: each level returns a map object. In addition it is not apparent that it can operate on an input list .
解决方案
Here is another solution using SSPipe library.
Note that all functions used here like map, filter, str, len, enumerate, str.format, str.join except p and px are builtin python functions and are you don't need to learn about new function names and API. The only thing you need is the p wrapper and px placeholder:
from sspipe import p, px
a = (
range(1, 50+1)
| p(map, px * 4)
| p(filter, px <= 170)
| p(filter, p(str) | p(len) | (px == 2))
| p(filter, px % 20 == 0)
| p(enumerate)
| p(map, p('Result[{0[0]}]={0[1]}'.format))
| p(' .. '.join)
)
print(a)