1. 程式人生 > >python lambda,filter,字典排序簡單應用

python lambda,filter,字典排序簡單應用

對於一個字典的簡單排序

lambda:在lambda後面直接跟變數,變數後面是冒號,冒號後面是表示式,表示式計算結果就是本函式的返回值,形式如下:

lambda arg1, arg2, ...argN : expression using arguments

filter:filter的中文含義是“過濾器”,在Python中,它起到了過濾器的作用,形式如下:

filter(function,iterable) function函式,iterable可迭代的物件、

簡單的小例項:

# -*- coding: utf-8 -*-

if __name__=="__main__":
    examine_scores = {"google":98, "baidu":95, "sougo":90, "360":80, "yahoo":90,"bing":98,"QQ":80,"IE":85}
    t=sorted(examine_scores.items(),key=lambda x:x[1],reverse=True)
    print(t)
    print("輸出成績表:")
    for i in t:
        print(i)
    
    print("輸出最高成績:")
    max_score=t[0][1]
    print(list(filter(lambda x:x[1]==max_score,t)))
    
    print("輸出最低成績:")
    min_score=t[len(t)-1][1]
    print(list(filter(lambda x:x[1]==min_score,t)))
    
    print("輸出平均成績:",sum(examine_scores.values())/len(examine_scores))

輸出結果:

輸出成績表: ('google', 98) ('bing', 98) ('baidu', 95) ('sougo', 90) ('yahoo', 90) ('IE', 85) ('360', 80) ('QQ', 80) 輸出最高成績: [('google', 98), ('bing', 98)] 輸出最低成績: [('360', 80), ('QQ', 80)] 輸出平均成績: 89.5