首頁  >  文章  >  後端開發  >  python sorted函數的介紹

python sorted函數的介紹

高洛峰
高洛峰原創
2017-03-04 17:29:372457瀏覽

前兩天學習了一下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 = name

p1 = Person('sherry',20)
p2 = Person('june',20)


if p1<p2:
print(&#39;p1:{} less than p2:{}&#39;.format([p1.name,p1.age],[p2.name,p2.age]))
else:
print(&#39;p1:{} gte than p2:{}&#39;.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 = {&#39;sherry&#39;:[18,&#39;male&#39;],&#39;june&#39;:[20,&#39;female&#39;],&#39;flora&#39;:[19,&#39;female&#39;],&#39;alina&#39;:[21,&#39;male&#39;]}

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 0

p1 = Person(&#39;sherry&#39;,20)
p2 = Person(&#39;june&#39;,20)


if p1<p2:
    print(&#39;p1:{} less than p2:{}&#39;.format([p1.name,p1.age],[p2.name,p2.age]))
else:
    print(&#39;p1:{} gte than p2:{}&#39;.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

更多python sorted函數的介紹相關文章請關注PHP中文網!


#
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn