1. Application of sorted () function
- The sorted () function can accept a parameter
- The sorted () function can also accept a key function to implement a custom sort.
- Sorted () can also accept the third parameter: reverse=true for reverse ordering
- An example of accepting a parameter is as follows:
Sorted ([5,-3,1]) ——————-> results [ -3,1,5] Sort by size
- Accepts two parameters: in addition to receiving the data to be sorted, you can also receive a function to sort the requirements of this function, for example: sorted ([5,-3,1],key=abs) ———— –> result: [1,-3,5]
Exercises: d=[(' Wu ', 98), (' Rang ', ","), (' Hao ', 76)] sorted by name and score respectively
The code is as follows:
#coding: UTF-8 def my_name(t): returnt[0] def my_score(t): returnt[1]#测试d=[(' Wu ',98),(' rang ', the),(' Hao ', the)]#按名字进行排序l1=sorted (d,key=my_name) print ("By_name sorted:", L1) l2=sorted (d,key=my_score) print ("By_score sorted", L2)
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Application of sorted () function in Python