Skip to main content
 首页 » 编程设计

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

2025年05月04日27youxin

我有以下类(class):

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

如何按人口顺序处理 Countries() 首都? 例如[“伦敦”、“巴黎”、“柏林”、“华盛顿特区”]

请您参考如下方法:

将你的类放在一个列表中,并根据 population 属性(你必须将其转换为整数才能正确排序)对它们进行排序:

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

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

我在 sorted() function 中使用了 key 参数告诉它根据 Countries.population 属性进行排序(使用 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'] 

或者您可以手动将它们排序,但我假设您希望计算机进行排序..:-)