Reputation: 71
Here is two vectors :
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = [3, 4, 5, 6, 7, 8, 9, 10]
Suppose I define Test
class this way :
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
When I execute the command list(map(Test, zip(a,b)))
, it says __init__() missing 1 required positional argument: 'b'
. I know if I have t = (1,2)
, then I can create an instance of Test
with inst = Test(*t)
. Can I apply *
to solve my problem using map
? Is there a workaround?
Upvotes: 0
Views: 480
Reputation: 21295
Yes. You can do this:
tests = list(map(lambda args: Test(*args), zip(a,b)))
Which takes the zip
values as argument to a lambda & unwraps them when calling Test()
This is pretty much what itertools.starmap
does - so that's another option:
tests = list(starmap(Test, zip(a,b)))
The better option is to use a list-comprehension which makes the code much more readable:
tests = [Test(arg_a, arg_b) for (arg_a,arg_b) in zip(a, b)]
Upvotes: 2