以下是一个示例代码,展示如何按照名称、人口和面积对国家的数组列表进行排序:
class Country:
def __init__(self, name, population, area):
self.name = name
self.population = population
self.area = area
def __repr__(self):
return f"Country({self.name}, {self.population}, {self.area})"
def sort_countries(countries):
sorted_countries = sorted(countries, key=lambda x: (x.name, x.population, x.area))
return sorted_countries
# 示例使用
countries = [
Country("China", 1400000000, 9600000),
Country("India", 1366000000, 3287000),
Country("United States", 331002651, 9629091),
Country("Indonesia", 273523615, 1904569),
Country("Pakistan", 220892340, 881912)
]
sorted_countries = sort_countries(countries)
for country in sorted_countries:
print(country)
输出结果:
Country(China, 1400000000, 9600000)
Country(India, 1366000000, 3287000)
Country(Indonesia, 273523615, 1904569)
Country(Pakistan, 220892340, 881912)
Country(United States, 331002651, 9629091)
在这个示例中,我们首先定义了一个Country
类,表示一个国家,具有名称、人口和面积属性。然后,我们定义了一个sort_countries
函数,它接受一个国家数组列表,并使用sorted
函数根据国家的名称、人口和面积进行排序。最后,我们使用示例数据创建了一个国家数组列表,并对其进行排序,并输出排序后的国家信息。
下一篇:按照名称(字母特定)排列列