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

使用方法:

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

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

例子:

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 “”, line 1, in 
 AttributeError: ‘tuple’ object has no attribute ‘sort’

对字典排序

c = {1: ‘D’, 2: ‘B’, 3: ‘B’, 4: ‘E’, 5: ‘A’}
 sorted© #对键进行排序
 [1, 2, 3, 4, 5]
 sorted(c.values()) #对值进行排序
 [‘A’, ‘B’, ‘B’, ‘D’, ‘E’]


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

使用方法:

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

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

例子:

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 “”, line 1, in 
 AttributeError: ‘tuple’ object has no attribute ‘sort’
#对字典排序
 c = {1: ‘D’, 2: ‘B’, 3: ‘B’, 4: ‘E’, 5: ‘A’}
 sorted© #对键进行排序
 [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)]

对字符串排序

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)]

how to sort list in Python