32-python基础-python3-sort()方法

 1 # 列表排序方法-sort()
 2 
 3 # 1,sort()方法当场修改
 4 spam = [1,3.4,2,2.5]
 5 spam.sort()
 6 # lst [1, 2, 2.5, 3.4]
 7 
 8 # 2,不能对既有数字又有字符串值的列表排序,因为 Python 不知道如何比较它们.注意 TypeError 错误
 9 spam = [1, 3, 2, 4, 'Alice', 'Bob']
10 spam.sort()
11 # Traceback (most recent call last):
12 # File "<pyshell#70>", line 1, in <module> pam.sort()
13 # TypeError: unorderable types: str() < int()
14 
15 # 3,sort()方法对字符串排序时,使用“ASCII 字符顺序”,而不是实际的字
16 # 典顺序。大写字母排在小写字母之前。因此在排序时,小写的 a 在大写的
17 # Z 之后。
18 spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']
19 spam.sort()
20 print(spam)
21 # ['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']
22 
23 # 4,如果需要按照普通的字典顺序来排序,就在 sort()方法调用时,将关键字参数
24 # key 设置为 str.lower。
25 spam = ['a', 'z', 'A', 'Z']
26 spam.sort(key=str.lower)
27 print(spam)
28 # ['a', 'A', 'z', 'Z']

猜你喜欢

转载自www.cnblogs.com/summer1019/p/11362964.html