是否有一个相当于Haskell的“let” [英] Is there a Python equivalent of the Haskell 'let'

查看:115
本文介绍了是否有一个相当于Haskell的“let”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在一个与Haskell'let'表达式等价的Python,它允许我写如下内容:

  list2 = (列表中的productId)中的[let(name,size)= lookup(productId))

如果不是,那么最具可读性的替代方案是什么?



为了澄清(条形码(productId)),公制(大小)=(lookup(productId)),使用以下语法:

  ))

相当于

 (name,size)= lookup(productId)
x =(barcode(productId),metric(size))

然而,第二个版本并不能很好地处理列表解析。

您可以使用临时列表理解

  [(barcode(productId),metric(size))用于名称,大小在[lookup(productId)]] [0] 

或等价地,生成器表达式

  next((barcode(productId),metric(size))为[lookup(productId)]中的名称,大小)

但这两者都非常可怕。

另一个(可怕的)方法是通过一个临时lambda, (条形码(productId),公制(大小)))(lookup(productId))$ b($) $ b






我认为推荐的Pythonic定义一个函数,如

  def barcode_metric(productId):
name,size = lookup(productId)
返回条形码(productId),公制(大小)
list2 = [productId在列表中的barcode_metric(productId)]


Is there a Python equivalent of the Haskell 'let' expression that would allow me to write something like:

list2 = [let (name,size)=lookup(productId) in (barcode(productId),metric(size)) 
            for productId in list]

If not, what would be the most readable alternative?

Added for clarification of the let syntax:

x = let (name,size)=lookup(productId) in (barcode(productId),metric(size))

is equivalent to

(name,size) = lookup(productId)
x = (barcode(productId),metric(size))

The second version doesn't work that well with list comprehensions, though.

解决方案

You could use a temporary list comprehension

[(barcode(productId), metric(size)) for name, size in [lookup(productId)]][0]

or, equivalently, a generator expression

next((barcode(productId), metric(size)) for name, size in [lookup(productId)])

but both of those are pretty horrible.

Another (horrible) method is via a temporary lambda, which you call immediately

(lambda (name, size): (barcode(productId), metric(size)))(lookup(productId))


I think the recommended "Pythonic" way would just be to define a function, like

def barcode_metric(productId):
   name, size = lookup(productId)
   return barcode(productId), metric(size)
list2 = [barcode_metric(productId) for productId in list]

这篇关于是否有一个相当于Haskell的“let”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆