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?
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.
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>]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With