使用python在class属性中存储对象列表或表示对象的字典列表更好吗?

时间:2019-02-11 01:39:39

标签: python dictionary object

说我要经常遍历列表。假设我将数据作为一连串的字典开始。有性能上的理由要使用另一个吗?

示例

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

选项1存储字典列表,并产生代表汽车的字典-

class DealershipLot:
    def __init__(self, data):
        self.cars_on_lot = data

    __iter__(self):
        for car in self.cars_on_lot:
            yield car

选项2存储汽车对象列表并产生汽车对象-

class DealershipLot:
    def __init__(self, data):
        self.cars_on_lot = []
        for car in data:
            self.cars_on_lot.append(Car(car))

    def __iter__(self):
        for car in self.cars_on_lot:
            yield car

选项3存储字典列表并产生汽车对象-

class DealershipLot:
    def __init__(self, data):
        self.cars_on_lot = data

    def __iter__(self):
        for car in self.cars_on_lot:
            yield Car(car)

0 个答案:

没有答案