内置函数提供的一个通用的排序方案,sorted(),filter()筛选函数,map()映射函数

lst = ['聊斋','西游记','三国演义','葫芦娃','水浒传','年轮','亮剑']
def func(s):
    return len(s) % 2
ll = sorted(lst,key=func,reverse=True)  # reverse = True 相当于从大到小排列
print(ll)  # ['西游记', '葫芦娃', '水浒传', '聊斋', '三国演义', '年轮', '亮剑']
# key:排序方案,sorted函数内部会把迭代对象中的每一个元素拿出来交给后面的key
# 后面的key计算出一个数字,作为当前这个元素的权重,整个函数根据权重重新进行排序

 

lst = [{"id":1, "name":'alex', "age":18},
 {"id":2, "name":'wusir', "age":16},
 {"id":3, "name":'taibai', "age":17}]

ll = sorted(lst,key=lambda el:el['age'])
print(ll)

filter()

lst = ['张无忌','张铁林','赵一宁','石可欣','马大帅']
def func(el):
    if el[0] == '':
        return False # 不想要的
    else:
        return True # 想要的

f = filter(func,lst)  # 将lst中的每一项传递给func,所有返回True的都会保留,所有返回False都会被清除
print('__iter__'in dir(f))  # 判断是否可以进行迭代
for e in f:
    print(e)
lst = ['张无忌','张铁林','赵一宁','石可欣','马大帅']


f = filter(lambda el:el[0]!='',lst)  # 将lst中的每一项传递给func,所有返回True的都会保留,所有返回False都会被清除
print('__iter__'in dir(f))  # 判断是否可以进行迭代
for e in f:
    print(e)

 

map()

映射函数

语法: map(function, iterable) 可以对可迭代对象中的每一个元素进行映射. 分别取执行
function

def func(e):
 return e*e
mp = map(func, [1, 2, 3, 4, 5])
print(mp)  # <map object at 0x0000000001DC71D0>
print(list(mp))  # [1, 4, 9, 16, 25]

 

lst1 = [1, 2, 3, 4, 5]
lst2 = [2, 4, 6, 8, 10]
print(list(map(lambda x, y: x+y, lst1, lst2))) # [3,6,9,12,15]
lst1 = [1, 2, 3]
lst2 = [2, 4, 6, 8, 10]
print(list(map(lambda x, y: x+y, lst1, lst2)))   # [3, 6, 9]

 也有水桶效应

posted on 2019-05-10 10:34  Little_Raccoon  阅读(136)  评论(0编辑  收藏  举报