美文网首页
python中sorted函数

python中sorted函数

作者: Daniel_go | 来源:发表于2018-10-13 15:27 被阅读0次

    sorted

    iterable:是可迭代类型;

    cmp:用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项;

    key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项;

    reverse:排序规则. reverse = True 或者 reverse = False,有默认值。

    返回值:是一个经过排序的可迭代类型,与iterable一样。

    注;一般来说,cmp和key可以使用lambda表达式

    举例:

    M=[('a', 1), ('b', 2), ('c', 6), ('d', 4), ('e', 3)]

    若:sorted(l, key=lambda x:x[0])

    则[('a', 1), ('b', 2), ('c', 6), ('d', 4), ('e', 3)]

    若:sorted(l, key=lambda x:x[1])

    则:[('a', 1), ('b', 2), ('e', 3), ('d', 4), ('c', 6)]

    举例

    L = [('b',2),('a',1),('c',3),('d',4)]

    >>>print sorted(L,cmp=lambda x,y:cmp(x[1],y[1]))

    [('a', 1), ('b', 2), ('c', 3), ('d', 4)]

    比较两个维度的大小。

    Python3中已经不能使用cmp()函数了,被如下五个函数替代:

    import operator      #首先要导入运算符模块

    operator.gt(1,2)      #意思是greater than(大于)

    operator.ge(1,2)      #意思是greater and equal(大于等于)

    operator.eq(1,2)      #意思是equal(等于)

    operator.le(1,2)      #意思是less and equal(小于等于)

    operator.lt(1,2)      #意思是less than(小于)

    相关文章

      网友评论

          本文标题:python中sorted函数

          本文链接:https://www.haomeiwen.com/subject/jpmoaftx.html