python sorted函數的小練習,pythonsorted函數

來源:互聯網
上載者:User

python sorted函數的小練習,pythonsorted函數

前兩天學習了一下socket編程,在向某大神請教問題時被嫌棄了,有一種還沒學會走就想跑的感覺。大神說我現在的水平應該去做一些像是操作檔案、序號等的小練習來加深理解。下面是他給我出的小練習:

1、datas = [['sherry',19,'female'],['flora',21,'female'],['june',15,'femal']],分別根據名字首字母和年齡進行排序輸出;

2、按照給定的輸出方式進行輸出比較結果,對Person類進行補充;

class_mates = {'sherry':[18,'male'],'june':[20,'female'],'flora':[19,'female'],'alina':[21,'male']}class Person(object):  def __init__(self,name,age):  self.name = namep1 = Person('sherry',20)p2 = Person('june',20)if p1<p2:print('p1:{} less than p2:{}'.format([p1.name,p1.age],[p2.name,p2.age]))else:print('p1:{} gte than p2:{}'.format([p1.name,p1.age],[p2.name,p2.age]))

就這麼簡單我竟做了一下午(打臉)

 def get_first(info):     first_value = info[0][0]     return first_value na = sorted(datas,key=get_first) print(na) def age_sort(info):     return info[1] print(sorted(datas,key=age_sort))
題目1
class_mates = {'sherry':[18,'male'],'june':[20,'female'],'flora':[19,'female'],'alina':[21,'male']}class Person(object):    def __init__(self,name,age):        self.name = name        self.age = age    def __lt__(self,others):        if(self.age<others.age):            return 1        elif(self.age==others.age):             if(self.name[0]<others.name[0]):                return 1            else:                return 0        return 0p1 = Person('sherry',20)p2 = Person('june',20)if p1<p2:    print('p1:{} less than p2:{}'.format([p1.name,p1.age],[p2.name,p2.age]))else:    print('p1:{} gte than p2:{}'.format([p1.name,p1.age],[p2.name,p2.age]))
題目2答案

查看python官方文檔,總結一下get到的知識。

1、sorted(iterable[, key][, reverse])

返回一個重新排序的list,有兩個可選的關鍵字參數(使用參數名而不是位置來指定參數)。

key 定義了一個帶參數的函數,提取list的某個元素作為這個函數的參數,傳回值作為你叫關鍵字,預設值是None(直接比較list的元素)

reverse是一個布爾值。True表示將list裡面的元素反向排序。

2、ln(a,b),當使用a<b的我時候,會自動調用__ln__(a,b)這個函數,因此我們要在類中重新定義__ln(a,b)__函數,自己定義什麼時候返回true什麼時候返回false。每一種類型都有自己的ln()函數,所以在重新定義的時候裡面也可以調用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.