Is there a Python equivalent of the Haskell 'let'

前端 未结 9 1267
青春惊慌失措
青春惊慌失措 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:07

    The multiple for clauses in b0fh's answer is the style I have personally been using for a while now, as I believe it provides more clarity and doesn't clutter the namespace with temporary functions. However, if speed is an issue, it is important to remember that temporarily constructing a one element list takes notably longer than constructing a one-tuple.

    Comparing the speed of the various solutions in this thread, I found that the ugly lambda hack is slowest, followed by the nested generators and then the solution by b0fh. However, these were all surpassed by the one-tuple winner:

    list2 = [ barcode(productID), metric(size)
              for productID in list
              for (_, size) in (lookup(productID),) ]
    

    This may not be so relevant to the OP's question, but there are other cases where clarity can be greatly enhanced and speed gained in cases where one might wish to use a list comprehension, by using one-tuples instead of lists for dummy iterators.

提交回复
热议问题