Discuss / Python / sorted作业

sorted作业

Topic source

L = [('Bob',75),('Adam',92),('Bart',66),('Lisa',88)]
#第一题,按照名字排序
def by_name(t):
    return t[0]#t为L的元素,('name',score),因此是t[0]而不是t[][0]

L2 = sorted(L,key= by_name)#sorted将key函数依次作用于L的每一个元素
print(L2)

#第二题,按照分数从高到低排序
L = [('Bob',75),('Adam',92),('Bart',66),('Lisa',88)]
def by_score(t):
    return t[1]

L2 = sorted(L,key = by_score,reverse=True)
print(L2)
  1. sorted将key函数依次作用于L的每一个元素,因此传到key函数的不在是L,而是L的元素('name',score)
  2. reverse=True 降序

  • 1

Reply