How to use the map function in Python? (How to rewrite a for loop?)

I have an array of classes and I want to create objects from them. It works:

classArray = [Auto, Wheel] objectArray = [] for myClass in classArray: objectArray += [myClass()] 

Can I use the map function to do the same?

  objectArray = map( ??? , classArray) 

My apologies if this is a stupid question. I am new to Python.

Thanks!

+4
source share
1 answer

You can use a list instead . Many consider them preferable for the map function.

 objectArrray = [ c() for c in classArray ] 

If you insist on using map , you can do

 map(lambda c: c(), classArray) 

Here I create an anonymous function with lambda that simply takes an element and calls it. If you are not familiar with map , it takes a 1-parameter function as the first argument.

+9
source

Source: https://habr.com/ru/post/1388542/


All Articles