当前位置:   article > 正文

sorted函数python_sorted函数

sorted函数python

sorted函数是python内置的,用来对可迭代对象排序的函数。此函数不会修改入参,返回一个已经排好序的list。

list对象的成员函数sort会直接修改对象的内容,如果不想修改,就可以使用内置的sorted函数来创建一个排好序的新对象:

>>> b

['a462d', 'abc', '34dfwe', '54fg', '1zp']

>>> c = sorted(b)

>>> c

['1zp', '34dfwe', '54fg', 'a462d', 'abc']

>>> b

['a462d', 'abc', '34dfwe', '54fg', '1zp']

>>> c = sorted(b, key=lambda x:x[2])

>>> c

['a462d', 'abc', '34dfwe', '54fg', '1zp']

>>> c = sorted(b, key=lambda x:x[2], reverse=True)

>>> c

['1zp', '54fg', '34dfwe', 'abc', 'a462d']

b还是原来的b,c是新的排好序的对象。注意sorted函数的key和reverse参数!sorted函数默认是从小到大排序,reverse=True时,就是从大到小!

sorted函数只接受一个可迭代对象作为入参,返回总是list对象:

>>> sorted((3,2,4,1,6))

[1, 2, 3, 4, 6]

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

[1, 2, 3, 4, 6]

>>> sorted({3,2,4,1,6})

[1, 2, 3, 4, 6]

关注sorted函数的stable特性(list.sort函数也有这个特性),stable特性保证了相同的两个元素或对象的顺序不会发生变化:

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

在python内置函数中,涉及排序的函数都有key参数,用法一样,比如:max和min,list.sort,以及本文的sorted函数。

-- EOF --

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/722931
推荐阅读
相关标签
  

闽ICP备14008679号