I have list myList = [[1, 2], [3, 4], [5, 6]]
which I can use assignment unpacking to get list_instance0, list_instance1, list_instance2 = myList
If I have a class:
class myClass():
def __init__(self, a: int, b: int):
self.a = a
self.b = b
def printAB(self):
return self.a, self.b
Now If I want to assign the list_instance[i]
I can do:
classInstance0=myClass(*list_instance0)
classInstance1=myClass(*list_instance1)
classInstance2=myClass(*list_instance2)
If I was to try
subClass0, subClass1, subClass2 = myClass(*list_instance0, *list_instance1, *list_instance2)
# error "myClass" is not iterable: __iter__ method not defined
So I was wondering is there a way to assign classInstance[i]
with list_instance[i]
to myClass
in a more dynamic way instead of having to assign each one individually?
>Solution :
You simply want to map MyClass
over your list.
from itertools import starmap
subClass0, subClass1, subClass2 = starmap(myClass, myList)
starmap
ensures the contents of each sublist are passed as separate arguments to myClass
, rather than the sublist itself passed as a single argument.
or you can use a list comprehension to be a little more explicit:
subClass0, subClass1, subClass2 = [myClass(*x) for x in myList]