Cac*_*ses 1 python variables class
我有以下课程:
class Countries(object):
def __init__(self, country_capital, country_population):
self.capital = country_capital
self.population = country_population
Run Code Online (Sandbox Code Playgroud)
以及连接到类的变量列表:
france = Countries("Paris", "66")
england = Countries("London", "53")
usa = Countries("Washington, DC", "318")
germany = Countries("Berlin", "80")
Run Code Online (Sandbox Code Playgroud)
我如何按人口顺序查看国家()首都?例如["伦敦","巴黎","柏林","华盛顿特区"]
将您的类放在一个列表中,并根据population属性(必须转换为整数才能正确排序)对它们进行排序:
[c.capital for c in sorted([france, england, usa, germany], key=lambda c: int(c.population))]
Run Code Online (Sandbox Code Playgroud)
这将使用列表解析提取只是从每个国家物体首都名,按人口排序的对象后.
我使用函数的key参数告诉它对属性进行排序(转换为数字):sorted()Countries.populationint()
>>> 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']
Run Code Online (Sandbox Code Playgroud)
或者你可以,你知道,手动将它们按顺序排列,但我认为你想让计算机进行排序.. :-)
| 归档时间: |
|
| 查看次数: |
37 次 |
| 最近记录: |