Is there a value in using map() vs for?

前端 未结 8 2731
误落风尘
误落风尘 2021-02-20 17:03

Does map() iterate through the list like \"for\" would? Is there a value in using map vs for?

If so, right now my code looks like this:

for item in item         


        
8条回答
  •  深忆病人
    2021-02-20 17:36

    You can write this using map like this:

    map(cls.my_func, items)
    

    replacing cls with the class of the items you are iterating over.

    As mentioned by Stephan202, this is not recommended in this case.

    As a rule, if you want to create a new list by applying some function to each item in the list, use map. This has the implied meaning that the function has no side effect, and thus you could (potentially) run the map in parallel.

    If you don't want to create a new list, or if the function has side effects, use a for loop. This is the case in your example.

提交回复
热议问题