Python中高阶函数---sorted,filter,map

sorted

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.

参数reverse

a = [1,2,3,4,5]
a1 = sorted(a,reverse=True)
print('逆序结果a1:{},a:{}'.format(a1,a))


输出:
逆序结果a1:[5, 4, 3, 2, 1],a:[1, 2, 3, 4, 5]

参数key

key可以接受函数:

l = [2,-3,5,-1,-8,2]
print('l:',l)
print('sorted(l):',sorted(l)) #默认升序排序
print('sorted(l,key=abs):',sorted(l,key=abs)) #abs为内置函数,绝对值

l1 = [[1,3,'a'],['e'],'dsfeee',[5,9]]
def func(l):
    return len(l)
print('sorted(l1,key=func):',sorted(l1,key=func)) #根据元素长度排序


输出:
l: [2, -3, 5, -1, -8, 2]
sorted(l): [-8, -3, -1, 2, 2, 5]
sorted(l,key=abs): [-1, 2, 2, -3, 5, -8]
sorted(l1,key=func): [['e'], [5, 9], [1, 3, 'a'], 'dsfeee']

通过key进行排序:

from operator import itemgetter,attrgetter

d = {'bob':13,'nacy':3,'kity':44,'sunny':31}
d1 = sorted(d,key=itemgetter(0))  #按key排序,返回value列表
d2 = sorted(d,key=itemgetter(1))  #按value排序,返回key列表
print('d1:',d1)
print('d2:',d2)
d3 = sorted(d.items(),key=itemgetter(1))#按value排序,返回字典元组列表
print('d3:',d3)

D = [('a',4,2),('b',1,4),('c',2,6),('d',1,1)]
D1 = sorted(D,key=itemgetter(1))
D2 = sorted(D,key=itemgetter(1,2)) #多级排序
print('D1',D1)
print('D2(多级排序)',D2)



输出:
d1: ['bob', 'kity', 'nacy', 'sunny']
d2: ['nacy', 'kity', 'bob', 'sunny']
d3: [('nacy', 3), ('bob', 13), ('sunny', 31), ('kity', 44)]
D1 [('b', 1, 4), ('d', 1, 1), ('c', 2, 6), ('a', 4, 2)]
D2(多级排序) [('d', 1, 1), ('b', 1, 4), ('c', 2, 6), ('a', 4, 2)]

filter

Init signature: filter(self, /, *args, **kwargs)
Docstring:     
filter(function or None, iterable) --> filter object

filter 函数的返回值是一个 filter 对象,使用 list 方法将 filter 函数的返回值转换为列表 

def clear_data(e):
    if isinstance(e,int) or isinstance(e,float):
        return True
    else:
        return False
    
l = ['e',5,8.9,[3,4],22,True,('a',3),0]
f = list(filter(clear_data,l))
print('filter:',f)
print('True ==1:',True ==1)



输出:
filter: [5, 8.9, 22, True, 0]
True ==1: True

map

Init signature: map(self, /, *args, **kwargs)
Docstring:     
map(func, *iterables) --> map object

map 函数的返回值也是一个 map 对象,它是 map 类的实例,使用 list 方法将其转换为列表 

def m(e):
    return e**2+1
l = [1,2,3,4]
r = list(map(m,l))
print('list(map(m,l)):',r)



输出:
list(map(m,l)): [2, 5, 10, 17]

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值