python中sort和sort()的区别

2018-04-18  本文已影响29人  慧琴如翌

区别:

  1. 首先sorted和sort 的区别主要在于sorted是将排序完的数据赋予给一个新变量,而sort则是在原变量的基础上直接进行排序,不产生新变量;
  2. 调用方式:
    list.sort() #list本身改变了顺序
    sorted(iterable)
  3. sort只能对iterable的列表排序,sorted既能对列表也包括任何iterable ;
In [201]: s3 = {1: 'D', 2: 'B', 4: 'B', 3: 'E', 5: 'A'}  #字典类型的

In [202]: sorted(s3)        #只能用sorted排序
Out[202]: [1, 2, 3, 4, 5]    
<font color=red>safds</font>
In [183]: s1 = 'python'

In [184]: s2 = ['c','a','b']

In [185]: sorted(s1)
Out[185]: ['h', 'n', 'o', 'p', 't', 'y']

In [186]: s1
Out[186]: 'python'

In [187]: sorted(s2)
Out[187]: ['a', 'b', 'c']

In [188]: s2
Out[188]: ['c', 'a', 'b']

In [189]: 

In [189]: s2.sort()

In [190]: s2
Out[190]: ['a', 'b', 'c']

In [191]: 

In [191]: s1.sort()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-191-e125c1850991> in <module>()
----> 1 s1.sort()

AttributeError: 'str' object has no attribute 'sort'

用法:

1. 原址排序:

列表有自己的sort方法,其对列表进行原址排序,既然是原址排序,那显然元组不可能拥有这种方法,因为元组是不可修改的

x = [4, 6, 2, 1, 7, 9]
x.sort()
print x # [1, 2, 4, 6, 7, 9]

2. 副本排序

x =[4, 6, 2, 1, 7, 9]
y = x[ : ]
y.sort()
print y #[1, 2, 4, 6, 7, 9]
print x #[4, 6, 2, 1, 7, 9]
注意:y = x[:] 通过分片操作将列表x的元素全部拷贝给y,如果简单的把x赋值给y:y = x,y和x还是指向同一个列表,并没有产生新的副本。

sorted返回一个有序的副本,并且类型总是列表,如下:

x =[4, 6, 2, 1, 7, 9]
y = sorted(x)
print y #[1, 2, 4, 6, 7, 9]
print x #[4, 6, 2, 1, 7, 9] 
1
print sorted('Python') #['P', 'h', 'n', 'o', 't', 'y']

复杂排序

In [147]: a= [('b',1), ('c',2), ('a',3)]

In [148]: a
Out[148]: [('b', 1), ('c', 2), ('a', 3)]

In [149]: d = sorted(a)

In [150]: d
Out[150]: [('a', 3), ('b', 1), ('c', 2)]

In [151]: a
Out[151]: [('b', 1), ('c', 2), ('a', 3)]

In [152]: c = a.sort()

In [153]: a
Out[153]: [('a', 3), ('b', 1), ('c', 2)]

In [154]: c

3. 给对象中的项排序

student_tuples = [
...     ('john', 'A', 15),
...     ('jane', 'B', 12),
...     ('dave', 'B', 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
The same technique works for objects with named attributes. For example:

>>> class Student:
...     def __init__(self, name, grade, age):
...         self.name = name
...         self.grade = grade
...         self.age = age
...     def __repr__(self):
...         return repr((self.name, self.grade, self.age))
>>> student_objects = [
...     Student('john', 'A', 15),
...     Student('jane', 'B', 12),
...     Student('dave', 'B', 10),
... ]
>>> sorted(student_objects, key=lambda student: student.age)   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

note:sorted(student_objects, key=lambda student: student.age)写法

4. 给对象中的两项排序

>>>sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

>>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

5. 根据含有子串的数目排序

例子如下:根据字符串含有"!"的个数进行排序

For example:

>>>> from operator import methodcaller
>>> messages = ['critical!!!', 'hurry!', 'standby', 'immediate!!']
>>> sorted(messages, key=methodcaller('count', '!'))
['standby', 'hurry!', 'immediate!!', 'critical!!!']

6. 升序和降序

默认是升序,也可以按照降序排序

# 按照升序和降序排序
def sort4():
    student_tuples = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
    print sorted(student_tuples, key=lambda student: student[2])  #[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
    print sorted(student_tuples, key=lambda student: student[2],reverse=True) #[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

7. 更复杂排序

更复杂地你可以构建多个步骤来进行更复杂的排序,例如对student数据先以age升序排列,再以grade降序排列。

>>> s = sorted(student_objects, key=attrgetter('age'))     # sort on secondary key
>>> sorted(s, key=attrgetter('grade'), reverse=True)       # now sort on primary key, descending
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

参考:https://www.cnblogs.com/sunny3312/archive/2017/01/07/6260472.html

上一篇下一篇

猜你喜欢

热点阅读