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

前端 未结 4 453
暖寄归人
暖寄归人 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条回答
  •  一生所求
    2020-12-24 05:45

    map is useful when you want to apply the function to every item of an iterable and return a list of the results. This is simpler and more concise than using a for loop and constructing a list.

    for is often more readable for other situations, and in lisp there were lots of iteration constructs that were written basically using macros and map. So, in cases where map doesn't fit, use a for loop.

    In theory, if we had a compiler/interpreter that was smart enough to make use of multiple cpus/processors, then map could be implemented faster as the different operations on each item could be done in parallel. I don't think this is the case at present, however.

提交回复
热议问题