I am trying to merge all cities in order by country UA , BE , etc etc , in a single chain list , but however I am getting only individual lists of each country - cities . I did the following approach using itertools
def crawl(self):
cities = ('AU','BE','CA','CH','CN','CZ','DE','ES','FR','GB','IE','IT','JP','KR','MX','NL','NZ','PL','RO','RU','SE','SG','US')
self.cities = dict()
for city in cities:
city_path = os.path.join(self.SITE_ROOT, 'cities', city)
with open(city_path, 'r') as file:
self.cities[city] = file.read().splitlines()
c = list(itertools.chain.from_iterable(zip(self.cities[city]))) # better.
print(c)
Current Output:
['Moscow', 'St. Petersburg', 'Sochi', 'Nizhny Novgorod', 'Yekaterinburg', 'Krasnodar', 'Tyumen']
['sweden', 'Stockholm', 'Malmø', 'Gothenburg', 'Göteborg', 'Uppsala', 'Solna']
['Singapore', 'Kallang']
['Los Angeles, CA', 'San Jose, CA', 'San Diego, CA', 'San Francisco, CA', 'Austin, TX', 'Dallas, TX', 'Arlington, VA', 'Washington, DC', 'Boston, MA', 'New York, NY', 'Chicago, IL', 'Minneapolis, MN', 'Denver, CO', 'Salt Lake City, UT']
Expected Output (all cities in a single list):
['Moscow', 'St. Petersburg', 'Sochi', 'Nizhny Novgorod', 'Yekaterinburg', 'Krasnodar', 'Tyumen','sweden', 'Stockholm', 'Malmø', 'Gothenburg', 'Göteborg', 'Uppsala', 'Solna','Singapore', 'Kallang','Los Angeles, CA', 'San Jose, CA', 'San Diego, CA', 'San Francisco, CA', 'Austin, TX', 'Dallas, TX', 'Arlington, VA', 'Washington, DC', 'Boston, MA', 'New York, NY', 'Chicago, IL', 'Minneapolis, MN', 'Denver, CO', 'Salt Lake City, UT']
Just create c
as an empty list before you start your loop, and add to it the individual lists of each country - cities you obtain in the loop:
def crawl(self):
cities = ('AU','BE','CA','CH','CN','CZ','DE','ES','FR','GB','IE','IT','JP','KR','MX','NL','NZ','PL','RO','RU','SE','SG','US')
self.cities = dict()
c = []
for city in cities:
city_path = os.path.join(self.SITE_ROOT, 'cities', city)
with open(city_path, 'r') as file:
self.cities[city] = file.read().splitlines()
c += list(itertools.chain.from_iterable(zip(self.cities[city]))) # better.
print(c)