Reputation: 1294
I have a list of lists as follows:
list = [['SYDNEY', 'to', 'SAN FRANCISCO'], ['SYDNEY', 'from' 'AUCKLAND'], ['HONG KONG', 'to', 'BEIJING'], ['TOKYO' 'to', 'SEOUL'], ['SAN FRANCISCO', 'from', 'LONDON'], ['SYDNEY', 'to', 'SHANGHAI'], ['KL', 'to', 'SYDNEY']]
I also have a class called 'City'
class City:
def __init__(self, name):
self.cityName= name
self.to_or_from = []
self.to_or_from_city = []
How can I use the list
to create objects for each city. For example, for Sydney, the object should look like this:
cityName = Sydney
to_or_from = ['to', 'from', 'to']
to_or_from_city = ['SAN FRANCISCO', 'AUCKLAND', 'SHANGHAI']
Please note that there is no need to consider KL
in the Sydney
object, however, the KL
object should contain Sydney
as follows:
cityName = KL
to_or_from = ['to']
to_or_from_city = ['SYDNEY']
In other words, if we have ['City1', 'to', 'City2']
, then the City2
object does not need to contain a 'from' City1
.
Upvotes: 0
Views: 312
Reputation: 15513
Question: How can I use the
_list
to create aclass City
object for each city
_list = [['SYDNEY', 'to', 'SAN FRANCISCO'],
['SYDNEY', 'from', 'AUCKLAND'],
['HONG KONG', 'to', 'BEIJING'],
['TOKYO', 'to', 'SEOUL'],
['SAN FRANCISCO', 'from', 'LONDON'],
['SYDNEY', 'to', 'SHANGHAI'],
['KL', 'to', 'SYDNEY']
]
class City:
def __init__(self, name):
self.cityName= name
self.to_or_from = []
self.to_or_from_city = []
def append(self, relation):
c1, r, c2 = relation
self.to_or_from.append(r)
self.to_or_from_city.append(c2)
def __str__(self):
return 'City:{}, {}'.format(self.to_or_from, self.to_or_from_city)
cities = {}
for relation in _list:
name = relation[0]
cities.setdefault(name, City(name)).append(relation)
for name, city in cities.items():
print('{}:{}'.format(name, city))
Output:
SYDNEY:City:['to', 'from', 'to'], ['SAN FRANCISCO', 'AUCKLAND', 'SHANGHAI'] HONG KONG:City:['to'], ['BEIJING'] TOKYO:City:['to'], ['SEOUL'] SAN FRANCISCO:City:['from'], ['LONDON'] KL:City:['to'], ['SYDNEY']
Upvotes: 1