python容器排序sort()和内建函数sorted()的区别
2013-09-15 16:57
931 查看
简单解释一下两函数:
sort(cmp=None, key=None, reverse=False)sorted(iterable, cmp=None, key=None, reverse=False)
sort是容器的函数,sorted是Python的内建函数
相同的参数:
cmp:用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项。cmp(e1, e2) 是带两个参数的比较函数, 返回值: 负数: e1 < e2, 0: e1 == e2, 正数: e1 > e2。 默认为 None, 即用内建的比较函数。
key:用列表元素的某个已命名的属性或函数(只有一个参数并且返回一个用于排序的值)作为关键字,有默认值,迭代集合中的一项。
reverse:排序规则,reverse = True 或者 reverse = False,有默认值。
sorted多一个参数iterable:待排序的可迭代类型的容器
>>> a=[1,3,5,2,9,4,7,8,6,0]
>>> a.sort()
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a=[1,3,5,2,9,4,7,8,6,0]
>>> sorted(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a
[1, 3, 5, 2, 9, 4, 7, 8, 6, 0]
对于一个无序的列表a,调用a.sort(),对a进行排序后返回a。
而对于同样一个无序的列表a,调用sorted(a),对a进行排序后返回一个新的列表,而对a不产生影响。
sort(cmp=None, key=None, reverse=False)sorted(iterable, cmp=None, key=None, reverse=False)
sort是容器的函数,sorted是Python的内建函数
相同的参数:
cmp:用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项。cmp(e1, e2) 是带两个参数的比较函数, 返回值: 负数: e1 < e2, 0: e1 == e2, 正数: e1 > e2。 默认为 None, 即用内建的比较函数。
key:用列表元素的某个已命名的属性或函数(只有一个参数并且返回一个用于排序的值)作为关键字,有默认值,迭代集合中的一项。
reverse:排序规则,reverse = True 或者 reverse = False,有默认值。
sorted多一个参数iterable:待排序的可迭代类型的容器
>>> a=[1,3,5,2,9,4,7,8,6,0]
>>> a.sort()
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a=[1,3,5,2,9,4,7,8,6,0]
>>> sorted(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a
[1, 3, 5, 2, 9, 4, 7, 8, 6, 0]
对于一个无序的列表a,调用a.sort(),对a进行排序后返回a。
而对于同样一个无序的列表a,调用sorted(a),对a进行排序后返回一个新的列表,而对a不产生影响。
相关文章推荐
- Python的排序函数Sort,Sorted
- python中排序,函数sort、sorted、argsort,collections.OrderedDict类
- python list排序sort和sorted的区别
- python 中方法 sort() 和函数sorted()的区别!!!!
- python的排序函数sort,sorted在列表排序和字典排序中的应用详解和举例
- Python中的排序函数argsort,sort,sorted
- python的排序函数sort,sorted在列表排序和字典排序中的应用详解和举例
- Python中的排序函数argsort,sort,sorted用法
- python的排序函数sort,sorted
- python sort() sorted() 与argsort()函数的区别
- python中列表排序sort()方法或者内建函数sorted()
- Python中排序常用到的sort 、sorted和argsort函数
- python sort、sorted高级排序技巧
- Python中利用sorted()函数排序的简单教程
- Python sort sorted函数详解
- Python笔记- 匿名函数lambda(),过滤函数filter(),求素数,排序sorted
- Python中排序常用到的sort 、sorted和argsort函数
- python sort sorted 排序详解
- 深入理解python中sort()与sorted()的区别
- Python:sorted 与 sort 的使用及区别