python sorted函數(shù)的小練習及解答
前兩天學習了一下socket編程,在向某大神請教問題時被嫌棄了,有一種還沒學會走就想跑的感覺。大神說我現(xiàn)在的水平應該去做一些像是操作文件、序列號等的小練習來加深理解。下面是他給我出的小練習:
1、datas = [['sherry',19,'female'],['flora',21,'female'],['june',15,'femal']],分別根據(jù)名字首字母和年齡進行排序輸出;
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('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))
答案
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官方文檔,總結一下get到的知識。
1、sorted(iterable[, key][, reverse])
返回一個重新排序的list,有兩個可選的關鍵字參數(shù)(使用參數(shù)名而不是位置來指定參數(shù))。
key 定義了一個帶參數(shù)的函數(shù),提取list的某個元素作為這個函數(shù)的參數(shù),返回值作為你叫關鍵字,默認值是None(直接比較list的元素)
reverse是一個布爾值。True表示將list里面的元素反向排序。
2、ln(a,b),當使用a<b的我時候,會自動調用__ln__(a,b)這個函數(shù),因此我們要在類中重新定義__ln(a,b)__函數(shù),自己定義什么時候返回true什么時候返回false。每一種類型都有自己的ln()函數(shù),所以在重新定義的時候里面也可以調用。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
jupyter notebook tensorflow打印device信息實例
這篇文章主要介紹了jupyter notebook tensorflow打印device信息實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python實現(xiàn)將Excel轉換為json的方法示例
這篇文章主要介紹了Python實現(xiàn)將Excel轉換為json的方法,涉及Python文件讀寫及格式轉換相關操作技巧,需要的朋友可以參考下2017-08-08
深入了解Python中Pytest Markers的使用方法
從這篇開始,逐一解決fixture是啥,mark是啥,參數(shù)request是啥,鉤子函數(shù)是啥,parametrize參數(shù)化是啥,這些問題,本片先介紹一下mark是啥,以及如何使用2023-09-09
Python-Flask:動態(tài)創(chuàng)建表的示例詳解
今天小編就為大家分享一篇Python-Flask:動態(tài)創(chuàng)建表的示例詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

