python--sort()和sorted()高級排序


1、list中的sort()方法: 

def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        pass
''' key:是排序的條件,可以是:key=int,key=len, key=lambda..
reverse:表示是否反序,默認從小到大,默認為Flase
'''
##一個list調用sort方法后,對原list進行排序
## 1、最簡單的排序
l = [5,2,3,1,4 ]
l .sort()
print(l)   ##輸出:[1, 2, 3, 4, 5]

l.sort(reverse=True)#反序
print(l)    ##輸出:[5, 4, 3, 2, 1]

##2、字符串排序
StrList = ['fb', 'bx', 'csw', 'qb', 'qqa', 'eeeed']
2.1 一般字典序排列,但是大寫在前,小寫在后!!
StrList.sort()
print(StrList) ##字符串列表是按照第一個字符的大小排序的
##輸出:['Fast', 'Smooth', 'fast', 'is', 'is', 'smooth']

2.2忽略大小寫,按abcd順序
StrList.sort(key=str.lower)
print(StrList) ##輸出:['Fast', 'fast', 'is', 'is', 'Smooth', 'smooth']

2.3按照字符串長度排序
StrList.sort(key=len)
print(StrList)##輸出:['is', 'is', 'fast', 'Fast', 'Smooth', 'smooth']

StrList.sort(key=len, reverse=True)#反序
print(StrList) ##輸出:['Smooth', 'smooth', 'fast', 'Fast', 'is', 'is']

其他:

  1、sort()配合lambda()進行排序:

1 l = [[2, 2, 3], [1, 4, 5], [5, 4, 9]]
2  l.sort(lambda x:x[0])  ##按照第一個元素進行排序
3 print(l)   ##輸出:[[1, 4, 5], [2, 2, 3], [5, 4, 9]]
4 '''
5     匿名函數的x,表示的是l列表中的每一個成員元素
6     
7     x[0] :表示列表里面列表的第一個成員元素
8 '''

   2、也可以對對對象的屬性進行排序

 

2、sorted()方法

 1 def sorted(*args, **kwargs): # real signature unknown
 2     """
 3     Return a new list containing all items from the iterable in ascending order.
 4     
 5     A custom key function can be supplied to customize the sort order, and the
 6     reverse flag can be set to request the result in descending order.
 7     """
 8 '''
 9 sorted(L)返回一個排序后的L,不改變原始的L;
  L.sort()是對原始的L進行操作,調用后原始的L會改變,沒有返回值。【所以a = a.sort()是錯的啦!a = sorted(a)才對!
11 sorted()適用於任何可迭代容器,list.sort()僅支持list(本身就是list的一個方法) 12 13 '''

 

 1、sort配合lambda進行排序

 2、sort配合lambda進行排序

  若是可迭代序列的成員元素是對象,那么同樣可以用sorted方法進行排序: 對象.成員變量

 1 >>> class Student:
 2         def __init__(self, name, grade, age):
 3                 self.name = name
 4                 self.grade = grade
 5                 self.age = age
 6         def __repr__(self):
 7                 return repr((self.name, self.grade, self.age))
 8 >>> student_objects = [
 9         Student('john', 'A', 15),
10         Student('jane', 'B', 12),
11         Student('dave', 'B', 10),
12 ]
13 >>> sorted(student_objects, key=lambda student: student.age)   # sort by age
14 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

 3、如果第一個排序條件相同,則按照第二個條件排序

a = [[2,3],[4,1],(2,8),(2,1),(3,4)]
b = sorted(a,key=lambda x: (x[0], -x[1]))
print(b)
'''
  b = sorted(a,key=lambda x:(條件a,條件b))  
'''

 4、字典排序:

1 ## 面試很可能會遇到
2 dic = {'a':2,'b':1}
3 
4 1、按照key排序
5     d = sorted(dic ,key = lambda k:k[0])
6  
7 2、按照values排序
8     e = sorted(dic , key = lambda k:k[1])

 5、字典的key-values互換

1 dic = { 'a':1, 'b':2,'c':3}
2 # 字典生成式
3 {values:key for key,values in dic.items()} ## 記住dic.items()變成了items[('a',1),('b',1)]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM