Cactuses
Cactuses

Reputation: 79

How do I print a list of all variable created for a class in order in Python?

I have the following class:

class Countries(object):
    def __init__(self, country_capital, country_population):
        self.capital = country_capital
        self.population = country_population

And a list of variables connected to the class:

france = Countries("Paris", "66")
england = Countries("London", "53")
usa = Countries("Washington, DC", "318")
germany = Countries("Berlin", "80")

How do I go about the Countries() Capitals in order of population? e.g. ["London", "Paris", "Berlin", "Washington, DC"]

Upvotes: 1

Views: 66

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121764

Put your classes in a list, and sort them based on the population attribute (which you must convert to an integer to correctly sort):

[c.capital for c in sorted([france, england, usa, germany], key=lambda c: int(c.population))]

This uses a list comprehension to extract just the capital name from each country object, after sorting those objects by population.

I used the key argument to the sorted() function to tell it to sort on the Countries.population attribute (converted to a number with int()):

>>> class Countries(object):
...     def __init__(self, country_capital, country_population):
...         self.capital = country_capital
...         self.population = country_population
...
>>> france = Countries("Paris", "66")
>>> england = Countries("London", "53")
>>> usa = Countries("Washington, DC", "318")
>>> germany = Countries("Berlin", "80")
>>> [c.capital for c in sorted([france, england, usa, germany], key=lambda c: int(c.population))]
['London', 'Paris', 'Berlin', 'Washington, DC']

Or you could just, you know, manually put them in order, but I assumed you wanted the computer to do the sorting.. :-)

Upvotes: 5

Eddo Hintoso
Eddo Hintoso

Reputation: 1442

DISCLAIMER

Before moving forward, I'd like to say that Martijn Pieters♦ answer is, to me, clearly superior because it is more efficient, readable, and understandable based on inference with English relatively to my answer.


MY SOLUTION

But... just for fun, this is an alternative solution using map, anonymous functions, and tuples (which may or may not be highly inefficient):

>>> countries = [france, england, usa, germany]
>>> countries_info = map(lambda c: (c.capital, int(c.population)), countries)
>>> print countries_info
[('Paris', 66), ('London', 53), ('Washington, DC', 318), ('Berlin', 80)]
>>>
>>> capitals_by_population = map(lambda c: c[0],  # extract first elem - capital
                                 sorted(countries_info, key = lambda c: c[1]))
>>> print capitals_by_population
['London', 'Paris', 'Berlin', 'Washington, DC']

BONUS: "BENCHMARKING"

So I'm just going to use Python's timeit module to see whether my solution or Martijn Pieters♦ answer is faster/slower.

from timeit import timeit

class Country(object):

    def __init__(self, country_capital, country_population):
        self.capital = country_capital
        self.population = country_population

france = Country("Paris", "66")
england = Country("London", "53")
usa = Country("Washington, DC", "318")
germany = Country("Berlin", "80")

countries = [france, england, usa, germany]

def sorted_capitals_by_population_martijn(countries):
    return [
        country.capital
        for country
        in sorted(countries, key = lambda c: int(c.population))
    ]

def sorted_capitals_by_population_eddo(countries):
    countries_info = map(lambda c: (c.capital, int(c.population)), countries)
    capitals_by_population = map(lambda c: c[0],
                                 sorted(countries_info, key = lambda c: c[1]))
    return capitals_by_population

nsim = 1 * (10 ** 6)

sort_times = {
    "martijn": timeit("sorted_capitals_by_population_martijn(countries)",
                      number=nsim,
                      setup="from __main__ import sorted_capitals_by_population_martijn, countries"),
    "eddo": timeit("sorted_capitals_by_population_eddo(countries)",
                   number=nsim,
                   setup="from __main__ import sorted_capitals_by_population_eddo, countries")
}

print(sort_times)

The output is below is displayed in seconds, and the results are expected:

{'eddo': 3.5935261249542236, 'martijn': 2.572805166244507}

As stated in my disclaimer, undoubtedly pick Martijn Pieters♦ answer over mine!

Upvotes: 0

Related Questions