Sorting Countries by Region

martyw wittem at kpnplanet.nl
Fri Nov 16 15:28:45 EST 2007


patrick.waldo at gmail.com wrote:
> Hi all,
> 
> I'm analyzing some data that has a lot of country data.  What I need
> to do is sort through this data and output it into an excel doc with
> summary information.  The countries, though, need to be sorted by
> region, but the way I thought I could do it isn't quite working out.
> So far I can only successfully get the data alphabetically.
> 
> Any ideas?
> 
> import xlrd
> import pyExcelerator
> 
> def get_countries_list(list):
it isn't a good idea to use a built-in object as a variable name
>     countries_list=[]
>     for country in countries:ii
>         if country not in countries_list:
>             countries_list.append(country)
> 
> EU = ["Austria","Belgium", "Cyprus","Czech Republic",
> "Denmark","Estonia", "Finland"]
> NA = ["Canada", "United States"]
> AP = ["Australia", "China", "Hong Kong", "India", "Indonesia",
> "Japan"]
> Regions_tot = {'European Union':EU, 'North America':NA, 'Asia
> Pacific':AP,}
i would create a class to capture country information, e.g.
class country(object):
     def __init__(self, name, size = 0, population = 0):
         self.name = name
         self.size = size
         self.poplation = population

     def __cmp__(self, other):
         if self.name < other.name:
             return -1
         elif self.name > other.name:
             return 1
         else:
             return 0

then you can set up the world as

world = {'NA': [country("United States"), country("Canada")], \
          'Europe': [country("Belgium"), country("Austria")]}


now you can sort and print it easy

for region in world:
     print region
     lands = world[region]
     lands.sort()
     for land in lands:
         print land.name

the sort works because the country objects have a method __cmp__

> 
> path_file = "c:\\1\country_data.xls"
> book = xlrd.open_workbook(path_file)
> Counts = book.sheet_by_index(1)
> countries= Counts.col_values(0,start_rowx=1, end_rowx=None)
> 
> get_countries_list(countries)
> 
> wb=pyExcelerator.Workbook()
> matrix = wb.add_sheet("matrix")
> 
> n=1
> for country in unique_countries:
>     matrix.write(n,1, country)
>     n = n+1
> 
> wb.save('c:\\1\\matrix.xls')
> 
> 
> 

i'm not familiar with the excel modules so i can't help you with that



More information about the Python-list mailing list