Which is better option, using Map or a For loop?

This question already has an answer here:

  • Are list-comprehensions and functional functions faster than “for loops”? 5 answers

  • As you've written it, definitely go with the for loop. map will create an unnecessary list (of all None since that is presumably the return value of myfunction ) on python2.x -- and on python3.x, it won't call your function at all until you actually iterate over the results!

    In other words, only use map when you actually want results that you are going to iterate over. Never use it for the side-effects of a function. For forward compatibility, never assume that map 's return value is a list -- If you need a list , use a list comprehension:

    [myfunction(e) for e in lst]
    

    If you do want an iterable and you are trying to decide between the analogous generator expression and map -- it sort of boils down to a matter of preference. The amount of difference in speed is almost always negligible. I think most prefer the generator expression in terms of aesthetics, but some projects (depending on the developers) may still prefer map . Be consistent with the surrounding code...


    One thing I think about is

    for element in list:
        # you can do something to element here
        myfunction(element)
    

    And there is no way to do the same thing in map(myfunction,list)

    And also some side effect consideration.

    链接地址: http://www.djcxy.com/p/69944.html

    上一篇: python:循环与理解

    下一篇: 哪个更好的选择,使用Map或For循环?