【Python 基础篇】Python知识点分解之 sort vs sorted

一、主要区别

1. sort 是应用在 list 上的方法,属于列表的成员方法,sorted 可以对所有可迭代的对象进行排序操作。

2. list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

3. sort使用方法为liit.sort(),而sorted使用方法为sorted(可迭代对象)。

二、排序基础

简单的升序排序是非常容易的。只需要调用sorted()方法。它返回一个新的list,新的list的元素基于小于运算符(lt)来排序。

>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]

你也可以使用list.sort()方法来排序,此时list本身将被修改。通常此方法不如sorted()方便,但是如果你不需要保留原来的list,此方法将更有效。

>>> a = [5, 2, 3, 1, 4]
>>> a.sort() # 原始列表已经被彻底改变
>>> a
[1, 2, 3, 4, 5] 

另一个不同就是list.sort()方法仅被定义在list中,相反地sorted()方法对所有的可迭代序列都有效。

>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) # 这里是 字典
[1, 2, 3, 4, 5]

如下:

>>> b=(3,5,7,8,2)  # 这里是一个 元组
>>> b.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'sort'
  
>>> sorted(b) # sorted对元组同样起作用
[2, 3, 5, 7, 8]

三、key参数/函数

python2.4开始,list.sort()和sorted()函数增加了key参数来指定一个函数,此函数将在每个元素比较前被调用。 例如通过key指定的函数来忽略字符串的大小写:

>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

key参数的值为一个函数,此函数只有一个参数且返回一个值用来进行比较。这个技术是快速的因为key指定的函数将准确地对每个元素调用

更广泛的使用情况是用复杂对象的某些值来对复杂对象的序列排序,例如:

>>> student_tuples = [
        ('john', 'A', 15),
        ('jane', 'B', 12),
        ('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(student_tuples, key=lambda student: student[1])
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(student_tuples, key=lambda student: student[0])
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

key=lambda 元素: 元素[字段索引]

例如:想对元素第二个字段排序,则key=lambda y: y[1],相对元素第一个字段排序,则key=lambda y: y[0]

备注:这里y可以是任意字母,等同key=lambda x: x[1]或者key=lambda x: x[0]

>>>list = [('a', 4), ('b', 2), ('c', 5), ('d', 3), ('e', 1)]
>>>print(sorted(list, key=lambda x: x[0])) #对第一个元素排序
>>>print(sorted(list, key=lambda y: y[1])) #对第二个元素排序
[('a', 4), ('b', 2), ('c', 5), ('d', 3), ('e', 1)]
[('e', 1), ('b', 2), ('d', 3), ('a', 4), ('c', 5)]

同样的技术对拥有命名属性的复杂对象也适用,例如:

>>> class Student:
    def __init__(self, name, grade, age):
        self.name = name
        self.grade = grade
        self.age = age
    def __repr__(self):
        return repr((self.name, self.grade, self.age))
>>> student_objects = [
    Student('john', 'A', 15),
    Student('jane', 'B', 12),
    Student('dave', 'B', 10),
]
>>> sorted(student_objects, key=lambda student: student.age)  # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

四、Operator 模块函数

上面的key参数的使用非常广泛,因此python提供了一些方便的函数来使得访问方法更加容易和快速。operator模块有itemgetter,attrgetter,从2.6开始还增加了methodcaller方法。使用这些方法,上面的操作将变得更加简洁和快速:

>>> from operator import itemgetter, attrgetter
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

operator模块还允许多级的排序,例如,先以grade,然后再以age来排序:

>>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

methodcaller的作用与 attrgetter 和 itemgetter 类似,它会自行创建函数,该函数会在对象上调用参数指定的方法:

>>> from operator import methodcaller 
>>> s = 'The time has come' 
>>> upcase = methodcaller('upper') 
>>> upcase(s)
'THE TIME HAS COME' 
>>> hiphenate = methodcaller('replace', ' ', '-') 
>>> hiphenate(s) 
'The-time-has-come'

如果把多个参数传给 itemgetter 或者 attrgetter,它构建的函数会返回提取的值构成的元组:

>>> metro_data = [('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889))]
>>> cc_name = itemgetter(1, 0) 
>>> for city in metro_data:
>>>     print(cc_name(city))
('JP', 'Tokyo') ('IN', 'Delhi NCR') 

如果参数名中包含 .(点号),attrgetter 会深入嵌套对象,获取指定的属性:

>>> from collections import namedtuple 
>>> LatLong = namedtuple('LatLong', 'lat long')  # ➊ 
>>> Metropolis = namedtuple('Metropolis', 'name cc pop coord')  # ➋ 
>>> metro_areas = [Metropolis(name, cc, pop, LatLong(lat, long))  # ➌ 
>>>     for name, cc, pop, (lat, long) in metro_data] 
>>> metro_areas[0] 
Metropolis(name='Tokyo', cc='JP', pop=36.933, coord=LatLong(lat=35.689722, long=139.691667)) 
>>> metro_areas[0].coord.lat  # ➍ 
35.689722 
>>> from operator import attrgetter 
>>> name_lat = attrgetter('name', 'coord.lat')  # ➎ 
>>> for city in sorted(metro_areas, key=attrgetter('coord.lat')):  # ➏   
>>>     print(name_lat(city))  # ➐
('Sao Paulo', -23.547778)
('Mexico City', 19.433333) 
('Delhi NCR', 28.613889)
('Tokyo', 35.689722) 
('New York-Newark', 40.808611)
❶ 使用 namedtuple 定义 LatLong。

❷ 再定义 Metropolis。

❸ 使用 Metropolis 实例构建 metro_areas 列表;注意,我们使用嵌套的元组拆包提取 (lat, long),然后使用它们构建 LatLong,作为 Metropolis 的 coord 属性。

❹ 深入 metro_areas[0],获取它的纬度。

❺ 定义一个 attrgetter,获取 name 属性和嵌套的 coord.lat 属性。

❻ 再次使用 attrgetter,按照纬度排序城市列表。

❼ 使用标号❺中定义的 attrgetter,只显示城市名和纬度。

五、升序和降序

list.sort()和sorted()都接受一个参数reverse(True or False)来表示升序或降序排序。例如对上面的student降序排序如下:

>>> sorted(student_tuples, key=itemgetter(2), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(student_objects, key=attrgetter('age'), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

六、排序的稳定性和复杂排序

从python2.2开始,排序被保证为稳定的。意思是说多个元素如果有相同的key,则排序前后他们的先后顺序不变。

>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
>>> sorted(data, key=itemgetter(0))
[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值