I've just started to learn Python. I have a list of lists where each element is a list and looks something like this: ['1', '2', '3']. I have a created a class like this:
class Car(object):
def __init__(self, a, b=0, c=0):
self.a = a
self.b = b
self.c = c
def setABC(self, a, b, c):
self.a = a
self.b = b
self.c = c
How do I create a new list where each element is an instance of this class, instead of the original list members?
I have tried something like this, but obviously it didn't work:
cars = cars.append(Car(cars[0], cars[1], cars[2]))
Also, I tried this:
cars = [Car(x.a, x.b, x.c) for x in cars]
You should unpack the nested list to create class object. You may create the list of Car
objects via using list comprehension as:
cars = [Car(*props) for props in properties_list]
where properties_list
is the list holding the properties you want to create your car with.
For example, if properties_list
is like:
properties_list = [[1, 2, 3], [4, 5, 6]]
then cars
will hold the list of Car
objects as:
cars = [
Car(a=1, b=2, c=3),
Car(a=4, b=5, c=6)
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.