python2.7 sorted cmp 排序函數


1. 不加參數

  >>>a = [3,2,1,4,5]

  >>>print sorted(a)

  >>>[1,2,3,4,5]

  >>>print a

  >>>[3,2,1,4,5]

分析:sorted 函數會返回一個排序好的序列,並不會更改原有序列,使用時注意記錄排序結果。

默認的排序按從小到大的升序返回。

2.參數reverse

  >>>a = [3,2,1,4,5]

  >>>print sorted(a,reverse=True)

  >>>[5,4,3,2,1]

分析:reverse會改變默認的原有排序順序。

3.參數cmp

  自定義判斷函數。更靈活的指定兩個對象的大小關系。例如按照學生的分數,從高到低對學生對象進行排序。

  首先寫一個學生類,包括姓名,分數,年齡。

class Student:
  def __init__(self, name, grade, age):
    self.name = name
    self.grade = grade
    self.age = age
  def __repr__(self):
    return "%s %d %d" % (self.name, self.grade, self.age)

def my_cmp(self, other):
    return self.grade - other.grade

student_objects = [
    Student('john', 92, 15),
    Student('jane', 94, 12),
    Student('dave', 94, 10)
    ]

print sorted(student_objects,cmp=my_cmp)
>>>  [john 92 15, jane 94 12, dave 94 10]

  比較函數一般規定大於的判定,sorted函數返回升序,我們需要從高到低,則增加reverse關鍵字

print sorted(student_objects,cmp=my_cmp,reverse=True)

>>>[jane 94 12, dave 94 10, john 92 15]

4.復雜cmp

  在一些場合,簡單的比較判斷無法滿足需求,判斷大小不是直觀地判斷簡單數據。

  例如:對學生排序,按分數高低排序,分數高的排在前面,若遇到相同分數則按年齡排序,年齡小的排在前面。

  分析:寫cmp函數,確定大於的判斷,分數高的大於分數低的,若分數相同,則年齡小的大於年齡大的

def my_cmp2(self,other):
    if self.grade > other.grade:
      return 1
    elif self.grade == other.grade:
      if self.age < other.age:
        return 1
      else:
        return -1
    else:
      return -1

print sorted(student_objects,cmp=my_cmp2,reverse=True)

>>>[dave 94 10, jane 94 12, john 92 15]

==========

2020年05月12日14:59:54 qsy


免責聲明!

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



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