在python3中对列表进行从左到右的操作


问题内容

有没有什么方法可以实现对列表中的操作的从左到右的非延迟调用python

例如 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

虽然我认识到很多人不喜欢上面的语法,但是我喜欢从左到右移动并随便添加任意操作的功能。

for当存在三个或更多操作时,python理解不容易理解。结果似乎是我们需要将所有内容分解为大块。

[f(a) for a in g(b) for b in h(c) for ..]

是否有机会提及上述方法?

注意:我尝试了一些库,包括toolz.functoolzpython3懒惰的评估使这一点变得复杂:每个级别都返回一个map对象。另外,尚不清楚它可以对输入进行操作list


问题答案:

@JohanL的答案很好地了解了标准python库中最接近的等效项。

我最终在2019年11月改编了Matt Hagy的要点,现在 pypi

https://pypi.org/project/infixpy/

from infixpy import *
a = (Seq(range(1,51))
     .map(lambda x: x * 4)
     .filter(lambda x: x <= 170)
     .filter(lambda x: len(str(x)) == 2)
     .filter( lambda x: x % 20 ==0)
     .enumerate() 
     .map(lambda x: 'Result[%d]=%s' %(x[0],x[1]))
     .mkstring(' .. '))
print(a)

  # Result[0]=20  .. Result[1]=40  .. Result[2]=60  .. Result[3]=80

其他答案中描述的其他方法

从pyxtension.streams导入流

从sspipe导入p,px

较旧的方法

我在2018年秋季发现了一个更具吸引力的工具包

https://github.com/dwt/fluent

在此处输入图片说明

在对可用的 第三方 库进行了相当全面的审查之后,Pipe
https://github.com/JulienPalard/Pipe似乎最符合需求。

您可以创建自己的管道功能。我将其用于整理以下所示的文本。粗线是工作发生的地方。所有这些@Pipe东西我只需要编写一次代码,然后就可以重复使用。

此处的任务是在第一个文本中关联缩写:

rawLabels="""Country: Name of country
Agr: Percentage employed in agriculture
Min: Percentage employed in mining
Man: Percentage employed in manufacturing
PS: Percentage employed in power supply industries
Con: Percentage employed in construction
SI: Percentage employed in service industries
Fin: Percentage employed in finance
SPS: Percentage employed in social and personal services
TC: Percentage employed in transport and communications"""

在第二个文本中带有关联的标签:

mylabs = "Country Agriculture Mining Manufacturing Power Construction Service Finance Social Transport"

这是功能操作 的一次性 编码(在后续管道中重用):

@Pipe
def split(iterable, delim= ' '):
    for s in iterable: yield s.split(delim)

@Pipe
def trim(iterable):
    for s in iterable: yield s.strip()

@Pipe
def pzip(iterable,coll):
    for s in zip(list(iterable),coll): yield s

@Pipe
def slice(iterable, dim):
  if len(dim)==1:
    for x in iterable:
      yield x[dim[0]]
  elif len(dim)==2:
    for x in iterable:
      for y in x[dim[0]]:
        yield y[dim[1]]

@Pipe
def toMap(iterable):
  return dict(list(iterable))

这是大 结局集成 在一个管道中:

labels = (rawLabels.split('\n') 
     | trim 
     | split(':')
     | slice([0])
     | pzip(mylabs.split(' '))
     | toMap )

结果:

print('labels=%s' % repr(labels))

labels={'PS': 'Power', 'Min': 'Mining', 'Country': 'Country', 'SPS': 'Social', 'TC': 'Transport', 'SI': 'Service', 'Con': 'Construction', 'Fin': 'Finance', 'Agr': 'Agriculture', 'Man': 'Manufacturing'}