简体   繁体   English

如何创建多个 class 对象并在 Python 中使用循环传递 arguments?

[英]How to create multiple class objects and pass arguments with loop in Python?

Here is the set of data,这是一组数据,

obj = [[A, B, 2], [D, A, 5] ,[B, C, 3]]

I would like to store this in the following class object我想将其存储在以下 class object

class Map():
 def __init__(self,start,destination,cost):
        self.start = start
        self.destination = destination
        self.cost = cost

I would like to store the obj in something like below with for loop我想用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

Anyone can help?任何人都可以帮忙吗?

A simple list comprehension will do the trick.一个简单的列表推导就可以解决问题。

obj = [Map(x, y, z) for x, y, z in obj]

You iterate over the original list, unpack each sublist, then call Map on each set of values.您遍历原始列表,解压缩每个子列表,然后对每组值调用Map

Even simpler, you can let Python unpack the sublists for you.更简单的是,您可以让 Python 为您解包子列表。

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

or或者

import itertools
obj = list(itertools.starmap(Map, obj))

Use a list:使用列表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM