zoukankan      html  css  js  c++  java
  • Python中sort以及sorted函数初探

    sorted(...)

    Help on built-in function sorted in module __builtin__:

    sorted(...)

        sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

    sort(...)

    Help on built-in function sort:
    sort(...)
        L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
        cmp(x, y) -> -1, 0, 1

    sorted与sort的差别

    1. sorted函数是内建函数,而sort是序列的内部函数,所以它们调用方式不一样,另外sorted函数多了一个系列迭代器參数

    2. sorted函数不改变參数系列。可是返回排好序的序列副本;而sort作为序列的内部函数,调用完后会对调用的序列进行排序

    以下的结果非常好的说明了这些:

    >>> list=[2,1]
    >>> x=sorted(list)
    >>> x
    [1, 2]
    >>> list
    [2, 1]
    >>> y=list.sort()
    >>> y
    >>> list
    [1, 2]

    sorted与sort的參数

    sorted与sort除了一个是序列作为參数,一个是序列调用该函数。其它參数差点儿全然一致,以下逐一来介绍其使用方法及效果:

    1. 默认使用方法

    因为sort函数的參数reverse,key,cmp都提供了缺省參数,所以我们能够直接不指定这些參数值调用该函数。

    可是它必须有一个前提。就是list中存放的类型是可比較的。否则就会弹出错误“Type Error: unorderable type"。

    2. reverse參数

    当取值为True时候就是倒序排。默觉得False正序从小到大排

    >>> list.sort(reverse=False)
    >>> list
    [1, 2]
    >>> list.sort(reverse=True)
    >>> list
    [2, 1]

    3. key參数

    key表示用来做比較的值。这个主要对自己定义的数据类型实用。以下用一个样例来诠释:
    # Definition for an interval.
    class Interval:
    	def __init__(self, s=0, e=0):
    		self.start = s
    		self.end = e
    
    # Initialize the Interval list
    list = []
    for i in range(10,7,-1):
    	for j in range(11,i,-1):
    		list.append(Interval(i,j))
    这里我们定义了Interval为[s,e]的数据结构而且初始化了。对于这个问题。显然我们用缺省的參数来调用会出错。由于我们没有提供可比較的函数来比較类型Interval。

    对于这种情况,我们就能够指定比較的key来解决。

    #Sort the Interval list
    list2 = sorted(list,key=lambda x:x.start)
    
    #Output the Interval list
    for x in list:
    	print("[%d,%d]"%(x.start,x.end))
    for x in list2:
    	print("[%d,%d]"%(x.start,x.end))
    这里我们基于Interval.start作为key进行排序了。

    但是接着问题来了。假设我不仅比較Interval.start,当Interval.start相等时候,还想比較Interval.end,该怎么办?
    #Sort the Interval list based on Interval.start and Interval.end
    list2 = sorted(list,key=lambda x:(x.start,x.end))
    我们用元祖(Interval.start,Interval.end)作为key来比較。而元祖有默认的cmp函数。这就达到了目标。

    4. cmp參数

    我们能够通过自己定义函数或则使用简洁的lambda来作为參数传给cmp
    #Sort the Interval list based on Interval.start and Interval.end
    def cmpInterval(a, b):
    	if a.start != b.start:
    		return cmp(a.start,b.start)
    	return cmp(a.end,b.end)
    list1 = sorted(list,cmp = cmpInterval)
    list2 = sorted(list,cmp = lambda x,y:cmp(x.start,y.start))
    只是比較遗憾的是发如今python 3.x中传入cmp函数会出现一个错误:TypeError: 'cmp' is an invalid keyword argument for this function
    这时候我们就须要使用key来绕过这个问题。另外一个建议就是我们尽量使用key而不是cmp来排序以提高执行速度。



  • 相关阅读:
    CodeForces 734F Anton and School
    CodeForces 733F Drivers Dissatisfaction
    CodeForces 733C Epidemic in Monstropolis
    ZOJ 3498 Javabeans
    ZOJ 3497 Mistwald
    ZOJ 3495 Lego Bricks
    CodeForces 732F Tourist Reform
    CodeForces 732E Sockets
    CodeForces 731E Funny Game
    CodeForces 731D 80-th Level Archeology
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/6747187.html
Copyright © 2011-2022 走看看