Map list by partial function vs lambda

前端 未结 3 1732
一生所求
一生所求 2021-02-05 11:24

I was wondering whether for most examples it is more \'pythonic\' to use lambda or the partial function?

For example, I might want to apply imap on some list, like add 3

相关标签:
3条回答
  • 2021-02-05 12:11

    To be truly equivalent to imap, use a generator expression:

    (x + 3 for x in mylist)
    

    Like imap, this doesn't immediately construct an entire new list, but instead computes elements of the resulting sequence on-demand (and is thus much more efficient than a list comprehension if you're chaining the result into another iteration).

    If you're curious about where partial would be a better option than lambda in the real world, it tends to be when you're dealing with variable numbers of arguments:

    >>> from functools import partial
    >>> def a(*args):
    ...     return sum(args)
    ... 
    >>> b = partial(a, 2, 3)
    >>> b(6, 7, 8)
    26
    

    The equivalent version using lambda would be...

    >>> b = lambda *args: a(2, 3, *args)
    >>> b(6, 7, 8)
    26
    

    which is slightly less concise - but lambda does give you the option of out-of-order application, which partial does not:

    >>> def a(x, y, z):
    ...    return x + y - z
    ...
    >>> b = lambda m, n: a(m, 1, n)
    >>> b(2, 5)
    -2
    
    0 讨论(0)
  • 2021-02-05 12:18

    lambda is certainly many times more common. Unless you're doing functional programming in an academic setting, you should probably steer away from functools.

    This is pythonic. No library needed, or even builtins, just a simple generator expression.

    ( x + 3 for x in my_list )
    

    This creates a generator, similar to imap. If you're going to make a list out of it anyway, use a list comprehension instead:

    [ x + 3 for x in my_list ]
    
    0 讨论(0)
  • 2021-02-05 12:25

    In the given example, lambda seems most appropriate. It's also easier on the eyes.

    I have never seen the use of partial functions in the wild.

    0 讨论(0)
提交回复
热议问题