Python内置函数sorted()和列表方法sort()的排序原理

首先定义自定义Country类,具有国家名称和面积这两个数据成员,并且实现了特殊方法__lt__()来支持<运算符。

 1 #!/usr/bin/env python  
 2 #-*- coding:utf-8 -*-  
 3 """ 
 4 @author:BanShaoHuan
 5 @file: Python内置函数sorted()和列表方法sort()的排序原理.py 
 6 @time: 2018/04/13
 7 @contact: banshaohuan@163.com
 8 @site:  
 9 @software: PyCharm 
10 
11 # code is far away from bugs with the god animal protecting
12     I love animals. They taste delicious.
13               ┏┓      ┏┓
14             ┏┛┻━━━┛┻┓
15             ┃      ☃      ┃
16             ┃  ┳┛  ┗┳  ┃
17             ┃      ┻      ┃
18             ┗━┓      ┏━┛
19                 ┃      ┗━━━┓
20                 ┃  神兽保佑    ┣┓
21                 ┃  永无BUG!   ┏┛
22                 ┗┓┓┏━┳┓┏┛
23                   ┃┫┫  ┃┫┫
24                   ┗┻┛  ┗┻┛ 
25 """  
26 
27 from random import randrange, shuffle
28 
29 class Country:
30     # 构造函数,初始化对象
31     def __init__(self, name, area):
32         self.__setName(name)
33         self.__setArea(area)
34 
35     def __setName(self, name):
36         assert isinstance(name, str), '国家名称必须是字符串'
37         self.__name = name
38 
39     def __setArea(self, area):
40         assert isinstance(area, int), '面积必须是整数'
41         self.__area = area
42 
43     # 返回国家名称
44     def getName(self):
45         return self.__name
46 
47     def getArea(self):
48         return self.__area
49 
50     # 支持<运算符
51     def __lt__(self, otherCountry):
52         return self.__area < otherCountry.__area
53 
54     def __str__(self):
55         return str((self.__name, self.__area))
56 
57 # 创建国家对象并添加至列表
58 countries = []
59 countryNames = list('abcdefghij')
60 shuffle(countryNames)#  这个shuffle是干嘛用的
61 for name in countryNames:
62     country = Country(name, randrange(10**2, 10**5))
63     countries.append(country)
64 
65 # 输出原始数据,不做任何排序
66 print('原始数据'.center(20, '='))
67 for country in countries:
68     print(country)
69 
70 # 使用内置函数sorted()函数排序,默认调用对象的__lt__()方法
71 print('默认函数'.center(20, '='))
72 for country in sorted(countries):
73     print(country)
74 
75 # 按国家名字进行排序,自定义排序规则
76 print('按国家名字排序'.center(20, '='))
77 for country in sorted(countries, key=lambda c:c.getName()):
78     print(country)
79 
80 # 按国家面积进行排序,自定义排序规则
81 print('按国家面积排序'.center(20, '='))
82 for country in sorted(countries, key=lambda c:c.getArea()):
83     print(country)

 

posted @ 2018-04-13 20:21  banshaohuan  阅读(573)  评论(0)    收藏  举报