对于python 列表,有一个方法 list.sort() ,另外还有一个内置函数sorted()
list.sort() 是对本身排序,不会产生新的对象。而sorted 接收一个可迭代对象,返回一个新的排好序的list
Help on built-in function sorted in module builtins: sorted(iterable, /, *, key=None, reverse=False) Return a new list containing all items from the iterable in ascending order. A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order
>>> help(list.sort) Help on method_descriptor: sort(...) L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
list.sort() 会把原始列表修改,return None ,当你不需要原始列表的时候,这个方法会更有效率。
>>> a=[3,5,2,1] >>> a.sort() >>> a [1, 2, 3, 5]
sorted() 这个方法用起来比较方便
>>> sorted([6,3,8,12,4]) [3, 4, 6, 8, 12] >>>
sorted() 接收可迭代对象
eg.
比如
>>> dic={4:'a',2:'b',3:'A',1:'h'} >>> sorted(dic) [1, 2, 3, 4]
Both list.sort() and sorted() have a key parameter to specify a function to be called on each list elementprior to making comparisons
list.sort()和sorted()都有一个关键参数来指定在每个列表元素上被调用的函数在进行比较之前。
for example:
>>> sorted("This is a test string from Andrew".split(), key=str.lower) ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
The value of the key parameter should be a function that takes a single argument and returns a key to usefor sorting purposes. This technique is fast because the key function is called exactly once for each inputrecord
key 参数的值应该是一个函数对象,这个函数对象带一个参数,返回一个key,这个key 就是排序的标准,
默认是升序排序
reverse 默认是false ,如果是true ,那就是降序排列
sorted 和list.sort() 的排序是稳定排序
于洋 回到顶部
转载于:https://www.cnblogs.com/yuyang26/p/7859742.html
相关资源:数据结构—成绩单生成器