When should I use a Map instead of a For Loop?

前端 未结 4 476
暖寄归人
暖寄归人 2020-12-24 05:12

This is relating to the following: (In Python Code)

for i in object:
     doSomething(i)

versus

map(doSomething, object)
         


        
4条回答
  •  萌比男神i
    2020-12-24 05:38

    Are you familiar with the timeit module? Below are some timings. -s performs a one-time setup, and then the command is looped and the best time recorded.

    1> python -m timeit -s "L=[]; M=range(1000)" "for m in M: L.append(m*2)"
    1000 loops, best of 3: 432 usec per loop
    
    2> python -m timeit -s "M=range(1000);f=lambda x: x*2" "L=map(f,M)"
    1000 loops, best of 3: 449 usec per loop
    
    3> python -m timeit -s "M=range(1000);f=lambda x:x*2" "L=[f(m) for m in M]"
    1000 loops, best of 3: 483 usec per loop
    
    4> python -m timeit -s "L=[]; A=L.append; M=range(1000)" "for m in M: A(m*2)"
    1000 loops, best of 3: 287 usec per loop    
    
    5> python -m timeit -s "M=range(1000)" "L=[m*2 for m in M]"
    1000 loops, best of 3: 174 usec per loop
    

    Note they are all similar except for the last two. It is the function calls (L.append, or f(x)) that severely affect the timing. In #4 the L.append lookup has been done once in setup. In #5 a list comp with no function calls is used.

提交回复
热议问题