Say I have a class, with a constructor that takes an integer. I have a list of integers. How do I use map() to create a list of objects of this class, each constructed with its respective integer?
3 Answers
As any other function?
>>> class Num(object):
... def __init__(self, i):
... self.i = i
...
>>> print map(Num, range(10))
[<__main__.Num object at 0x100493450>, <__main__.Num object at 0x100493490>, <__main__.Num object at 0x1004934d0>, <__main__.Num object at 0x100493510>, <__main__.Num object at 0x100493550>, <__main__.Num object at 0x100493590>, <__main__.Num object at 0x1004935d0>, <__main__.Num object at 0x100493610>, <__main__.Num object at 0x100493650>, <__main__.Num object at 0x100493690>]
Comments
map(lambda x: MyClass(..., x,...), list_of_ints)
Also consider using list comprehension instead of map:
[MyClass(..., x, ...) for x in list_of_ints]
Either of the above will return a list of objects of your class, assuming MyClass(..., x,...) is your class and list_of_ints is your list of integers.
3 Comments
Cristian Ciupitu
@J.F.Sebastian, the question does not say that the constructor takes only one parameter of an integer type, so I don't think this answer deserves a -1.
jfs
@CristianCiupitu: I've not downvoted it. Though I interpret the question as the constructor having the only argument i.e., the OP might not know that classes are first class citizens in particular you can pass them as function parameters in addition they are callable.
Cristian Ciupitu
@J.F.Sebastian, ok, it seems it was just a coincidence. Good point.
Checkout itertools.starmap.
In [1]: import itertools
In [2]: class C:
...: def __init__(self, arg1, arg2):
...: pass
...:
In [3]: classes = itertools.starmap(C, [(1,2), (3,4)])
In [4]: print list(classes)
[<__main__.C instance at 0x10e99b7e8>, <__main__.C instance at 0x10e99b830>]