List comprehension vs map

前端 未结 11 1794
长情又很酷
长情又很酷 2020-11-21 04:39

Is there a reason to prefer using map() over list comprehension or vice versa? Is either of them generally more efficient or considered generally more pythonic

11条回答
  •  清酒与你
    2020-11-21 04:59

    I ran a quick test comparing three methods for invoking the method of an object. The time difference, in this case, is negligible and is a matter of the function in question (see @Alex Martelli's response). Here, I looked at the following methods:

    # map_lambda
    list(map(lambda x: x.add(), vals))
    
    # map_operator
    from operator import methodcaller
    list(map(methodcaller("add"), vals))
    
    # map_comprehension
    [x.add() for x in vals]
    

    I looked at lists (stored in the variable vals) of both integers (Python int) and floating point numbers (Python float) for increasing list sizes. The following dummy class DummyNum is considered:

    class DummyNum(object):
        """Dummy class"""
        __slots__ = 'n',
    
        def __init__(self, n):
            self.n = n
    
        def add(self):
            self.n += 5
    

    Specifically, the add method. The __slots__ attribute is a simple optimization in Python to define the total memory needed by the class (attributes), reducing memory size. Here are the resulting plots.

    As stated previously, the technique used makes a minimal difference and you should code in a way that is most readable to you, or in the particular circumstance. In this case, the list comprehension (map_comprehension technique) is fastest for both types of additions in an object, especially with shorter lists.

    Visit this pastebin for the source used to generate the plot and data.

提交回复
热议问题