Python--sorted()函数

sorted()是Python里面很初级的函数,小伙伴们都用过,但是大家对sorted()用法知道多少呢?

内容主要来自于Python.org,有兴趣的可以自己看看。
以下代码在Python 3.4.4 Shell下运行

首先是最常见的用法,直接对数组进行排序操作:
<code>
>>>sorted([1,6,5,3,6,8,99,0])
[0, 1, 3, 5, 6, 6, 8, 99]
</code>

对数组a进行排序可以用sorted(a)或者a.sort()都可以,那么二者有什么区别呢?

主要区别有两个:

  1. sorted()函数不会改变对数组本身进行修改
    <code>
    >>> a = [1,6,5,3,6,8,99,0]
    >>> sorted(a)
    [0, 1, 3, 5, 6, 6, 8, 99]
    >>> a
    [1, 6, 5, 3, 6, 8, 99, 0]
    </code>
    而 list.sort()会对list进行修改:
    <code>
    >>> a = [1, 6, 5, 3, 6, 8, 99, 0]
    >>> a.sort()
    >>> a
    [0, 1, 3, 5, 6, 6, 8, 99]
    </code>

  2. list.sort()函数只使用与数组,而sorted()还能用于其他数据结构:
    <code>
    >>> b = {1:’a’,3:’b’,7:’d’,4:’4′,2:’4′}
    >>> sorted(b)
    [1, 2, 3, 4, 7]
    >>> b
    {1: ‘a’, 2: ‘4’, 3: ‘b’, 4: ‘4’, 7: ‘d’}
    >>> b.sort()
    Traceback (most recent call last):
    File “<pyshell#10>”, line 1, in <module>
    b.sort()
    AttributeError: ‘dict’ object has no attribute ‘sort’
    </code>

值得注意的是这里字典经过sorted()处理之后顺序发生变化,因为字典本身就是无序的,在Python 3.4.4 Shell中就算不排序也会按键值顺序显示。

使用sorted()或者list.sort()时可以添加参数

Key

key即排序的依据:
<code>
>>> sorted(“I am working in Hefei, Anhui Province”.split())
[‘Anhui’, ‘Hefei,’, ‘I’, ‘Province’, ‘am’, ‘in’, ‘working’]
>>> sorted(“I am working in Hefei, Anhui Province”.split(),key = str.lower)
[‘am’, ‘Anhui’, ‘Hefei,’, ‘I’, ‘in’, ‘Province’, ‘working’]
</code>
句子拆分成单词后排序会按照首字母的ASCII码排序,不过在添加了key = str.lower参数之后,就全部按照小写形式的ASCII码排序了。

看下面这段代码:
<code>
>>> a = [
(1,2,3),
(3,4,2),
(2,1,7),
]
>>> sorted(a,key = lambda x: x[1])
[(2, 1, 7), (1, 2, 3), (3, 4, 2)]
>>> sorted(a,key = lambda x: x[2])
[(3, 4, 2), (1, 2, 3), (2, 1, 7)]
>>> sorted(a)
[(1, 2, 3), (2, 1, 7), (3, 4, 2)]
</code>
像这样的元组组成的数组可以使用key参数决定按哪个参数排序。

同样可以使用key = object.attribute来对象的属性来排列对象。

前面提到了字典排序,字典直接排序是对键进行排序,那么如何对值进行排序呢:
<code>
>>> b = {1:’a’,3:’b’,7:’d’,4:’c’,2:’k’}
>>> sorted(b)
[1, 2, 3, 4, 7]
>>> sorted(b,key = b.__getitem__)
[1, 3, 4, 7, 2]
>>> sorted(b.items(),key = lambda a:a[0])
[(1, ‘a’), (2, ‘k’), (3, ‘b’), (4, ‘c’), (7, ‘d’)]
>>> sorted(b.items(),key = lambda a:a[1])
[(1, ‘a’), (3, ‘b’), (4, ‘c’), (7, ‘d’), (2, ‘k’)]
</code>

operator 模块

operator模块中提供了itemgetter ,attrgetter,methodcaller两个key函数,使用方法如下:
<code>
>>> from operator import itemgetter
>>> a = [
(1,2,7),
(3,4,2),
(2,2,3),
]
>>> sorted(a,key = itemgetter(1))
[(1, 2, 7), (2, 2, 3), (3, 4, 2)]
>>> sorted(a,key = itemgetter(1,2))#先按第二列排序,再按第三列排序
[(2, 2, 3), (1, 2, 7), (3, 4, 2)]
</code>
至于attrgetter是用来将对象来按属性排列用的,而methodcaller是用来按类内部某一方法的返回值来排序的。用法同理。

升序降序

<code>
>>> sorted(a,key = itemgetter(1),reverse = True)
[(3, 4, 2), (1, 2, 7), (2, 2, 3)]
>>> sorted(a,key = itemgetter(1),reverse = False)
[(1, 2, 7), (2, 2, 3), (3, 4, 2)]
</code>

可以注意到排序参数相同的两个元组会按照原有顺序排列。

    原文作者:dalalaa
    原文地址: https://www.jianshu.com/p/c53b2b522001
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞