高阶函数-排序
- 把一个序列按照给定算法进行排序
- key:在排序前对每个元素进行key函数运算,可以理解成按照key函数定义的逻辑进行排序
- python2和python3相差巨大
help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
# 排序的案例
a = [65,854,5,12,65,48,654,98,6,48,65,12,28,6,7,2]
al = sorted(a, reverse=True)
print(al)
[854, 654, 98, 65, 65, 65, 48, 48, 28, 12, 12, 7, 6, 6, 5, 2]
# 排序案例2
a = [-43,23,45,6,-23,2,-5465]
# 按照绝对值进行排序
# abs是求绝对值的意思
# 即按照绝对值的倒叙排列
al = sorted(a, key=abs, reverse=True)
print(al)
[-5465, 45, -43, 23, -23, 6, 2]
# sorted案例
astr = ['Wdad','dsfgsd','wecs','rgbdsada','ggdswera']
str1 = sorted(astr)
print(str1)
str2 = sorted(astr, key=str.lower)
print(str2)
['Wdad', 'dsfgsd', 'ggdswera', 'rgbdsada', 'wecs']
['dsfgsd', 'ggdswera', 'rgbdsada', 'Wdad', 'wecs']