Is there a Python equivalent of the Haskell 'let'

前端 未结 9 1213
青春惊慌失措
青春惊慌失措 2020-12-29 21:38

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 (ba         


        
相关标签:
9条回答
  • 2020-12-29 22:09

    Only guessing at what Haskell does, here's the alternative. It uses what's known in Python as "list comprehension".

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

    You could include the use of lambda:, as others have suggested.

    0 讨论(0)
  • 2020-12-29 22:16

    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]
    
    0 讨论(0)
  • 2020-12-29 22:16

    There is no such thing. You could emulate it the same way let is desugared to lambda calculus (let x = foo in bar <=> (\x -> bar) (foo)).

    The most readable alternative depends on the circumstances. For your specific example, I'd choose something like [barcode(productId), metric(size) for productId, (_, size) in zip(productIds, map(lookup, productIds))] (really ugly on second thought, it's easier if you don't need productId too, then you could use map) or an explicit for loop (in a generator):

    def barcodes_and_metrics(productIds):
        for productId in productIds:
            _, size = lookup(productId)
            yield barcode(productId), metric(size)
    
    0 讨论(0)
提交回复
热议问题