说我要经常遍历列表。假设我将数据作为一连串的字典开始。有性能上的理由要使用另一个吗?
示例
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)