Map list by partial function vs lambda

前端 未结 3 1737
一生所求
一生所求 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
    

提交回复
热议问题