下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、sortinghow torelease2.7.5guidovan rossumfred l. drake, jr., editorseptember 04, 2013python software foundationemail: contents1sorting basicsi2key functionsii3operatormodule functionsii4ascending and descendingiii5sort stabilityand complex sortsiii6the old way using decorate-sort-undeco
2、rateiii7the old way using the cmp parameteriv8odd and endsvauthorandrew dalke andraymond hettingerrelease 0.1python lists have a built-inlist.sort()method that modi?es the list in-place. there is also a sorted()built-in function that builds anew sorted list from an iterable.in this document, we expl
3、ore the various techniques for sorting data using python.1 sortingbasicsa simple ascending sort is very easy: just call the sorted()function. it returns a new sorted list:sorted( 5,2,3,1,4)1,2,3,4,5you can also use the list.sort()method of a list. it modi?es the list in-place (and returns none to av
4、oidconfusion). usually it slessconvenient than sorted()- but if you dontneed the original list, it sslightly moreef?cient.a= 5,2,3,1,4a. sort()a1,2,3,4,5another difference is that the list.sort()method is only de?ned for lists.in contrast, the sorted()function accepts any iterable.sorted( 1:d ,2:b ,
5、3:b ,4:e ,5:a )1,2,3,4,52 key functionsstarting with python 2.4, both list.sort()and sorted()added a key parameter to specify a function to becalled on eachlist element prior to making comparisons.for example, here sa case-insensitive string comparison:sorted( thisisateststringfromandrew. split(),ke
6、y =str. lower) a,andrew, from , is ,string, test , this the value of the key parameter should be a function that takes a single argument and returns a key to use forsorting purposes. this technique is fast becausethe key function is called exactly once for eachinput record.a common pattern is to sor
7、t complex objects using someof the objectsindices as keys. for example:student_tuples= ( john , a,15),( jane , b,12),( dave, b,10),sorted(student_tuples,key =lambdastudent:student2)#sortbyage( dave, b,10),( jane , b,12),( john , a,15)the same technique works for objects with named attributes. for ex
8、ample:classstudent:def_init_(self,name,grade,age):= nameself.grade=gradeself.age= agedef_repr_(self):returnrepr(,self.grade,self.age)student_objects=student( john ,a,15),student( jane ,b,12),student( dave,b,10),sorted(student_objects,key =lambdastudent:student. age)#sortbyage( dave
9、, b,10),( jane , b,12),( john , a,15)3 operatormodulefunctionsthekey-functionpatternsshownabove are verycommon,so pythonprovidesconveniencefunctionsto make accessor functionseasier and faster.the operatormodule has operator.itemgetter(),operator.attrgetter(), and starting in python 2.5 a operator.me
10、thodcaller()function.using those functions, the above examples become simpler and faster:fromoperatorimportitemgetter,attrgettersorted(student_tuples,key =itemgetter(2)( dave, b,10),( jane , b,12),( john , a,15)sorted(student_objects,key =attrgetter(age)( dave, b,10),( jane , b,12),( john , a,15)the
11、 operator module functions allow multiple levels of sorting. for example, to sort by grade then by age: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)the operator.method
12、caller()function makes method calls with ?xed parameters for eachobject beingsorted.for example, the str.count()method could be used to compute message priorityby counting thenumber of exclamation marks in a message:messages= critical!,hurry! ,standby ,immediate! sorted(messages,key =methodcaller(co
13、unt,! ) standby ,hurry!, immediate!,critical!4 ascendingand descendingboth list.sort()and sorted()accept a reverse parameter with a boolean value.this is used to ?agdescending sorts. for example, to get the student data in reverse age order:sorted(student_tuples,key =itemgetter(2),reverse=true )( jo
14、hn , a,15),( jane , b,12),( dave, b,10)sorted(student_objects,key =attrgetter(age),reverse=true )( john , a,15),( jane , b,12),( dave, b,10)5 sort stabilityand complexsortsstarting with python 2.2, sorts are guaranteed to be stable. that means that when multiple records have the samekey, their origi
15、nal order is preserved.data= (red ,1),( blue ,1),( red ,2),( blue ,2)sorted(data,key =itemgetter(0)( blue , 1),( blue , 2),( red , 1),( red , 2)notice how the two records for blue retain their original order so that ( blue , 1)is guaranteed to precede( blue , 2) .this wonderful property lets you bui
16、ld complex sorts in a seriesof sorting steps. for example, to sort the studentdata by descending grade and then ascending age, do the age sort ?rst and then sort again using grade:s=sorted(student_objects,key =attrgetter(age )# sortonsecondarykeysorted(s,key =attrgetter(grade),reverse=true )# nowsor
17、tonprimarykey,de( dave, b,10),( jane , b,12),( john , a,15)the timsort algorithm usedin python doesmultiple sortsef?ciently becauseit cantake advantageof any orderingalready present in a dataset.6 the old way usingdecorate-sort-undecoratethis idiom is called decorate-sort-undecorate after its three
18、steps:? first, the initial list is decorated with new values that control the sort order.? second, the decorated list is sorted.? finally, the decorations are removed, creating a list that contains only the initial values in the new order.for example, to sort the student data by grade using the dsu
19、approach:decorated=(student. grade,i,student)fori,studentinenumerate(student_objectsdecorated. sort()studentforgrade,i,studentindecorated#undecorate( john , a,15),( jane , b,12),( dave, b,10)this idiom works becausetuples arecompared lexicographically;the?rst items arecompared; if they arethe sameth
20、en the second items are compared, and so on.it is not strictly necessary in all casesto include the index i in the decorated list, but including it gives two bene?ts:? the sort is stable if two items have the samekey, their order will be preserved in the sorted list.? the original items do not have
21、to be comparable becausethe ordering of the decorated tuples will be deter-mined by at most the ?rst two items. so for example the original list could contain complex numbers whichcannot be sorted directly.another name for this idiom is schwartzian transform , after randal l. schwartz, who populariz
22、ed it among perlprogrammers.for large lists andlists where the comparison information is expensive to calculate, and python versions before 2.4,dsu is likely to be the fastestway to sort the list. for 2.4 andlater, key functions provide the samefunctionality.7 the old way usingthe cmp parametermany
23、constructs given in this howto assumepython 2.4 or later. before that, there was no sorted()builtinand list.sort()took no keyword arguments. instead, all of the py2.x versions supported a cmp parameter tohandle user speci?ed comparison functions.in python 3, the cmp parameter was removed entirely (a
24、spart of a larger effort to simplify and unify the language,eliminating the con?ict between rich comparisons and the _cmp_()magic method).in python 2, sort()allowed an optional function which can becalled for doing the comparisons. that functionshould take two arguments to be compared and then retur
25、n a negative value for less-than, return zero if they areequal, or return a positive value for greater-than. for example, we can do:defnumeric_compare(x,y):returnx-ysorted( 5,2,4,1,3,cmp=numeric_compare)1,2,3,4,5or you can reverse the order of comparison with:defreverse_numeric(x,y):returny-xsorted(
26、 5,2,4,1,3,cmp=reverse_numeric)5,4,3,2,1when porting code from python 2.x to 3.x, the situation canarise when you have the usersupplying a comparisonfunction and you needto convert that to a key function. the following wrapper makesthat easyto do:defcmp_to_key(mycmp):convertacmp=functionintoakey=fun
27、ctionclassk( object):def_init_( self,obj,*args):self. obj= objdef_lt_( self,other):returnmycmp( self. obj,other. obj)0def_eq_( self,other):returnmycmp( self. obj,other. obj)=0def_le_( self,other):returnmycmp( self. obj,other. obj)=0def_ne_( self,other):returnmycmp( self. obj,other. obj)!=0returnkto
28、convert to a key function, just wrap the old comparison function:sorted( 5,2,4,1,3,key =cmp_to_key(reverse_numeric)5,4,3,2,1in python 2.7, the functools.cmp_to_key()function was added to the functools module.8 odd and ends? for locale aware sorting, use locale.strxfrm()for a key function or locale.s
29、trcoll()for acomparison function.? the reverse parameter still maintains sort stability(so that records with equal keys retain their originalorder). interestingly, that effect can be simulated without the parameter by using the builtin reversed()function twice:data= (red ,1),( blue ,1),( red ,2),( blue ,2)assertsorted(data,reverse=true )=list( reversed( sorted( reversed(data)? to c
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025-2030中国合成特种纤维织物行业竞争动态与销售前景预测报告
- 门诊导医知识培训
- 单片机课程学习小结
- 公司职业规划模板
- 扶梯救援行动预案
- 天然气泄漏应急处理方案
- 第9课 这是我的家 第一课时 课件(内嵌音视频)2025-2026学年道德与法治一年级下册统编版
- 集体主义教育主题班会
- 2025年吉林松原市初二学业水平地生会考考试题库(附含答案)
- 打工小伙职业规划视频
- 2026四川德阳市什邡市教育和体育局选调高(职)中教师13人备考题库附答案详解
- 2026江西赣州市安远县东江水务集团有限公司第一批人员招聘10人备考题库含答案详解(b卷)
- 企业一般固废管理制度
- 2026年花样滑冰赛事品牌建设与营销创新案例研究
- 北师大版数学七年级下册知识点归纳总结
- 电梯井整体提升搭设安全专项施工方案(完整版)
- 项目RAMS系统保证计划SAP
- 《2020室性心律失常中国专家共识(2016共识升级版)》要点
- 人教A版(2019)高中数学必修第二册 基本立体图形 第2课时圆柱、圆锥、圆台、球与简单组合体的结构特征课件
- 国家开放大学《四史通讲》形考任务专题1-6自测练习参考答案
- 混凝土机械建筑施工机械
评论
0/150
提交评论