0

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 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

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?

2 Answers 2

1

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.

Even simpler, you can let Python unpack the sublists for you.

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

or

import itertools
obj = list(itertools.starmap(Map, obj))
Sign up to request clarification or add additional context in comments.

Comments

0

Use a list:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.