如何在Python中创建多个类对象并使用循环传递参数?

如何在Python中创建多个类对象并使用循环传递参数?,python,python-2.7,loops,constructor,Python,Python 2.7,Loops,Constructor,这是一组数据 obj = [[A, B, 2], [D, A, 5] ,[B, C, 3]] 我想将其存储在以下类对象中 class Map(): def __init__(self,start,destination,cost): self.start = start self.destination = destination self.cost = cost 我想用for循环将obj存储在下面这样的东西中 obj[0].start =

这是一组数据

obj = [[A, B, 2], [D, A, 5] ,[B, C, 3]]
我想将其存储在以下类对象中

class Map():
 def __init__(self,start,destination,cost):
        self.start = start
        self.destination = destination
        self.cost = cost
我想用for循环将obj存储在下面这样的东西中

obj[0].start = A
obj[0].destination = B
obj[0].cost = 2
....
obj[2].start = B
obj[2].destination = C
obj[2].cost = 3


任何人都可以帮忙吗?

简单的列表理解就可以了

obj = [Map(x, y, z) for x, y, z in obj]
迭代原始列表,解压缩每个子列表,然后对每组值调用
Map

更简单的是,您可以让Python为您解压子列表

obj = [Map(*args) for args in obj]

使用列表:

maps = []
for object in obj:
    maps.append(Map(object[0], object[1], object[2]))
maps = []
for object in obj:
    maps.append(Map(object[0], object[1], object[2]))