如何在Python中按顺序打印为类创建的所有变量的列表?

时间:2016-02-29 11:41:26

标签: python class variables

我有以下课程:

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

我如何按人口顺序查看国家()首都? 例如[“伦敦”,“巴黎”,“柏林”,“华盛顿特区”]

2 个答案:

答案 0 :(得分:5)

将您的类放入列表中,并根据mac属性(必须转换为整数才能正确排序)对它们进行排序:

population

在按人口对这些对象进行排序后,这会使用list comprehension从每个国家/地区对象中提取 大写名称。

我使用sorted() function[c.capital for c in sorted([france, england, usa, germany], key=lambda c: int(c.population))] 参数告诉它对key属性进行排序(转换为Countries.population的数字):

int()

或者你可以,你知道,手动将它们按顺序排列,但我认为你想让计算机进行排序......: - )

答案 1 :(得分:0)

声明

在向前迈进之前,我想说Martijn Pieters♦ answer对我来说显然更优越,因为相对于我的回答,基于对英语的推断,它更有效率,可读性和可理解性。

我的解决方案

但是......只是为了好玩,这是使用map,匿名函数和元组(可能是也可能不是非常低效)的替代解决方案:

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

奖金:“基准”

所以我将使用Python的timeit模块来查看我的解决方案或Martijn Pieters♦ answer是否更快/更慢。

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)

以下输出显示为秒,结果是预期的:

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

如我的免责声明中所述,毫无疑问选择Martijn Pieters♦ answer而不是mine