11

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 3

22

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>]
Sign up to request clarification or add additional context in comments.

Comments

4
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

@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.
@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.
@J.F.Sebastian, ok, it seems it was just a coincidence. Good point.
1

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>]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.