python列表操作程序_在python3中对列表进行从左到右的操作

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值