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

前端 未结 8 2920
误落风尘
误落风尘 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:22

    The main advantage of map is when you want to get the result of some calculation on every element in a list. For example, this snippet doubles every value in a list:

    map(lambda x: x * 2, [1,2,3,4])  #=> [2, 4, 6, 8]
    

    It is important to note that map returns a new list with the results. It does not modify the original list in place.

    To do the same thing with for, you would have to create an empty list and add an extra line to the for body to add the result of each calculation to the new list. The map version is more concise and functional.

提交回复
热议问题