程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Sorting methods of lists in Python operation summary sharing

編輯:Python

python Sort the list

Just remember python in List Of sort Method ( perhaps sorted Built-in functions ) Usage of .

keyword :

python Sort the list python Dictionary sort sorted

List And the elements of it can be all kinds of things , character string , Dictionaries , Self defined classes, etc .

sorted Function usage is as follows :

sorted(data, cmp=None, key=None, reverse=False)

among ,data It's the data to be sorted , You can make List perhaps iterator, cmp and key It's all functions , These two functions act on data To produce a result ,sorted Methods sort based on this result .

cmp(e1, e2) Is a comparison function with two parameters , Return value : negative : e1 < e2, 0: e1 == e2, Positive numbers : e1 > e2. The default is None, Using the built-in comparison function .

key It's a function with one parameter , Used to extract comparison values for each element . The default is None, That is to compare each element directly .

Usually , key and reverse Than cmp Much faster , Because for each element they only process once ; and cmp I'll deal with it many times .

To illustrate by an example sorted Usage of :

1. Right tuple Composed of List Sort

students =[(‘john’,‘A’,15),(‘jane’,‘B’,12),(‘dave’,‘B’,10),]

use key Function order (lambda See notes for usage of 1)

sorted(students, key=lambda student : student[2])# sort by age
[(‘dave’,‘B’,10),(‘jane’,‘B’,12),(‘john’,‘A’,15)]

use cmp Function order

sorted(students, cmp=lambda x,y : cmp(x[2], y[2]))# sort by age
[(‘dave’,‘B’,10),(‘jane’,‘B’,12),(‘john’,‘A’,15)]

use operator Function to speed up , The above sort is equivalent to :(itemgetter See notes for usage of 2)

from operator import itemgetter, attrgette
sorted(students, key=itemgetter(2))

use operator Function for multi-level sorting

sorted(students, key=itemgetter(1,2))# sort by grade then by age
[(‘john’,‘A’,15),(‘dave’,‘B’,10),(‘jane’,‘B’,12)]

2. Sort by Dictionary

d ={‘data1’:3,‘data2’:1,‘data3’:2,‘data4’:4}
sorted(d.iteritems(), key=itemgetter(1), reverse=True)
[(‘data4’,4),(‘data1’,3),(‘data3’,2),(‘data2’,1)]

That's all for this sharing ~ Pay attention before you go , Thank you for reading ~


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved