6、sorted()對分別按名字和成績排序


假設我們用一組tuple表示學生名字和成績:

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] 

請用sorted()對上述列表分別按名字和成績排序:

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

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]

#先按名字排序:
def by_name(t):
    return t[0].lower()   #t是tuple,t[0]是姓名(字符串)!!!
L2 = sorted(L, key=by_name)
print(L2)

#再按成績從高到低排序:
def by_score(t):
    return t[1]
L2 = sorted(L, key=by_score)
print(L2)

tuple類型本身沒有lower()方法,t[0]是tuple的第一個元素,t[1]是tuple的第二個元素,以此類推!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM