python用sort和sorted对多维列表、字典、字符串进行排序

sort()是列表的一个排序方法,直接修改原列表,没有返回值。
sorted()使用范围更广,不局限于列表,能接受全部迭代器,返回排好序的新列表。python

使用方法:web

list.sort(*, key=None, reverse=None) 
sorted(iterable[, key][, reverse])

key 是带一个参数的函数,表示用什么方式排序。
reverse 表示排序结果是否反转markdown

例子:svg

>>> a = [2, 4, 7, 1, 8, 5]
>>> sorted(a)
[1, 2, 4, 5, 7, 8]          #返回一个排好序的列表
>>> a.sort()                #sort()没有返回值,可是a已经被改变了
>>> a
[1, 2, 4, 5, 7, 8]
>>> 
#对元祖排序
>>> b = (2, 4, 7, 1, 8, 5)    #定义一个元祖类型
>>> sorted(b)                 #能够用sorted排序
[1, 2, 4, 5, 7, 8]
>>> b.sort()                  #可是sort不行
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'sort'
>>> 
#对字典排序
>>> c = {1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}    
>>> sorted(c)                 #对键进行排序
[1, 2, 3, 4, 5]
>>> sorted(c.values())      #对值进行排序
['A', 'B', 'B', 'D', 'E']
>>>
#对字符串排序
>>> s = 'cts'
>>> sorted(s)        
['c', 's', 't']      # 若是直接用sorted那么会将排序结果放入列表中,而且以字符的形式。
>>> "".join(sorted(s))   #至关于将字符链接起来转成字符串
'cst'
#多维列表排序
>>> d = [[5,2],[3,4],[9,7],[2,6]]
>>> d.sort()
>>> d
[[2, 6], [3, 4], [5, 2], [9, 7]]
>>> d = [[5,2],[3,4],[9,7],[2,6]]
>>> sorted(d)
[[2, 6], [3, 4], [5, 2], [9, 7]]     #都默认以第一维排序
>>> d = [[5,2],[3,4],[9,7],[2,6]]
>>> sorted(d, key = lambda x:x[1])    #若是要指定第二维排序:
[[5, 2], [3, 4], [2, 6], [9, 7]]
>>>
#多个参数排序:
>>> from operator import itemgetter    #要用到itemgetter函数
>>> e = [('hi', 'A', 27),('hello', 'C', 90),('yo', 'D', 8)]
>>> sorted(e, key=itemgetter(2))     #以第三列排序
[('yo', 'D', 8), ('hi', 'A', 27), ('hello', 'C', 90)]
>>> sorted(e, key=itemgetter(1,2))   #结合第二和第三列拍,先排第二列
[('hi', 'A', 27), ('hello', 'C', 90), ('yo', 'D', 8)]
>>> 

默认状况下都是升序,若是想降序,将reverse参数设为True
还有注意的是,若是不想改变原列表的值,那么就不要用sort。函数