我刚刚开始学习Python。我有一个列表列表,其中每个元素都是一个列表,看起来像这样:[' 1',' 2',' 3']。我创建了一个这样的类:
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
如何创建一个新列表,其中每个元素都是此类的实例,而不是原始列表成员?
我尝试过类似的东西,但显然它没有用:
cars = cars.append(Car(cars[0], cars[1], cars[2]))
另外,我试过这个:
cars = [Car(x.a, x.b, x.c) for x in cars]
答案 0 :(得分:3)
您应该解压缩嵌套列表以创建类对象。您可以使用 list comprehension 创建Car
个对象列表:
cars = [Car(*props) for props in properties_list]
其中properties_list
是包含您要创建汽车的属性的列表。
例如,如果properties_list
如下:
properties_list = [[1, 2, 3], [4, 5, 6]]
然后cars
会将Car
个对象列表保存为:
cars = [
Car(a=1, b=2, c=3),
Car(a=4, b=5, c=6)
]