python中sort和sorted函数的区别

python中sort和sorted函数的区别
python中的sort和sorted都属于排序函数
但是两者有用一些区别
sort()函数排序是对列表本身进行排序,使用这个函数后,原来的list列表也会发生改变,而且调用方式为
列表名.sort(),而且不可另外赋给一个列表

sorted的函数是对列表排序后不改变原来的列表,会另外生成一个列表,调用方式为sorted(列表名)

例题:

 a=[1,2,9,5,3]
>>> a.sort()
>>> a
[1, 2, 3, 5, 9]
>>> atest=a.sort()
>>> atest
>>> print(atest)
None
>>> b=[9,3,6,4]
>>> b.sorted()
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    b.sorted()
AttributeError: 'list' object has no attribute 'sorted'
>>> btest=b.sorted()
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    btest=b.sorted()
AttributeError: 'list' object has no attribute 'sorted'
>>> sorted(b)
[3, 4, 6, 9]
>>> b
[9, 3, 6, 4]
>>> x=sorted(b)
>>> x
[3, 4, 6, 9]
>>> 
posted @ 2019-12-06 17:58  X_J  阅读(158)  评论(0编辑  收藏  举报