溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python中sorted函數(shù)的原理是什么

發(fā)布時間:2021-05-14 16:23:16 來源:億速云 閱讀:277 作者:Leah 欄目:開發(fā)技術(shù)

python中sorted函數(shù)的原理是什么?針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

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

2、按照給定的輸出方式進行輸出比較結(jié)果,對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('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]))

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

題目1

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))

題目2答案

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 0

p1 = 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]))

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

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

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

key 定義了一個帶參數(shù)的函數(shù),提取list的某個元素作為這個函數(shù)的參數(shù),返回值作為你叫關(guān)鍵字,默認值是None(直接比較list的元素)

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

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

python有哪些常用庫

python常用的庫:1.requesuts;2.scrapy;3.pillow;4.twisted;5.numpy;6.matplotlib;7.pygama;8.ipyhton等。

關(guān)于python中sorted函數(shù)的原理是什么問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI