sort排序用法

Python】 sorted函數html

咱們須要對List、Dict進行排序,Python提供了兩個方法
對給定的List L進行排序,
方法1.用List的成員函數sort進行排序,在本地進行排序,不返回副本
方法2.用built-in函數sorted進行排序(從2.4開始),返回副本,原始輸入不變python

--------------------------------sorted---------------------------------------
>>> help(sorted)
Help on built-in function sorted in module __builtin__:

sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
---------------------------------sort----------------------------------------
>>> help(list.sort)
Help on method_descriptor:

sort(...)
    L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
    cmp(x, y) -> -1, 0, 1
-----------------------------------------------------------------------------

iterable:是可迭代類型;
cmp:用於比較的函數,比較什麼由key決定;
key:用列表元素的某個屬性或函數進行做爲關鍵字,有默認值,迭代集合中的一項;
reverse:排序規則. reverse = True  降序 或者 reverse = False 升序,有默認值。
返回值:是一個通過排序的可迭代類型,與iterable同樣。app

參數說明:
(1)  cmp參數
 
cmp接受一個函數,拿整形舉例,形式爲:
def f(a,b):
     return a-b
若是排序的元素是其餘類型的,若是a邏輯小於b,函數返回負數;a邏輯等於b,函數返回0;a邏輯大於b,函數返回正數就好了
 
(2)  key參數
 
 key也是接受一個函數,不一樣的是,這個函數只接受一個元素,形式以下
def f(a):
     return len(a)
key接受的函數返回值,表示此元素的權值,sort將按照權值大小進行排序
 
(3) reverse參數
接受False 或者True 表示是否逆序
以上知識來自於:https://www.cnblogs.com/sysu-blackbear/p/3283993.html
python解決https://www.hackerrank.com/challenges/nested-list/problem的問題
 1 def f(student):  # 排序函數
 2     return student[1]
 3 def choice(student,second,min_count):#判斷學生列表長度
 4     if len(student)>3:
 5         while second>0:
 6             second -= 1
 7             print(student[min_count+second][0])
 8     else:
 9        for i in range(second):
10             print(student[min_count+i][0])
11 
12 def second_index(student):  # 求出第二小的成績的下表
13     min_count = 0
14     min_score = student[0][1]
15     for one in student:
16         if one[1] == min_score:
17             min_count += 1
18     return min_count
19 
20 
21 def second_count(studnet, min_count):  # 求出第二小的成績出現的次數
22     second_count = 0
23     second_score = student[min_count][1]
24     for one in student[min_count:]:
25         if one[1] == second_score:
26             second_count += 1
27     return second_count
28 
29 if __name__ == '__main__':
30     student=[]
31     i=0
32     for x in range(int(input())):
33         name = input()
34         score = float(input())
35         list=[name,score]
36         student.append(list)
37     else:
38         student.sort(key=f)
39     min_count=second_index(student)#得出第二大數的下標
40     second=second_count(student,min_count)#得出第二小的數出現的次數
41     choice(student,second,min_count)
View Code
相關文章
相關標籤/搜索