python 高级函数_python高阶函数

一、lambda表达式

用法: lambda 参数列表:函数体

def minus(x,y):

return x-y

#print(minus(4,3)) 1

minus_lambda = lambda x,y : x - y

#print(minus_lambda(4,3)) 1

三元运算符

condition = True ##条件可以改变

print(1 if condition else 2) ##1

condition = False

print(1 if condition else 2) ##2

二、map函数

用法:map(函数,可迭代对象)

#map函数 map(函数,可迭代对象)

list1 = [1,2,3,4,5]

r = map(lambda x: 2*x, list1)

print(list(r)) ##[2, 4, 6, 8, 10] ##需要加list强转数据类型

m1 = map(lambda x, y : x * x + y, [1,2,3,4,5],[1,2,3,4,5])

print(list(m1)) ##[2, 6, 12, 20, 30] 5*5+5=30

三、filter过滤器

用法: filter(函数或空,可迭代的对象)

def is_not_none(s):

return s and len(s.strip()) > 0 ##去掉两边空格总长度大于0认为不是空的

list2 = [' ','','hello','greedy',None,'ai']

result = filter(is_not_none, list2)

print(list(result)) ##['hello', 'greedy', 'ai']

四、reduce函数

需要导入reduce模块

用法:reduce[函数,序列(可迭代),初始化一个值(可选))]

from functools import reduce

f = lambda x, y : x - y

re = reduce(f, [1,2,3,4,5]) ##1-2-3-4-5 -13

print(re)

re_final = reduce(f, [1,2,3,4,5], 10)

print(re_final) ##初始化为10 10-1-2-3-4-5 = -1

五、推导式

1. 列表推导式

根据已有列表推导出新的列表

list1 = [1,2,3,4,5,6]

list2 = [i + i for i in list1]

list3 = [i**4 for i in list1]

##有选择行的筛选一下

list4 = [i*i for i in list1 if i < 4] ##小于4的再做转换 1 2 3

print(list1) #[1, 2, 3, 4, 5, 6]

print(list2) #[2, 4, 6, 8, 10, 12]

print(list3) #[1, 16, 81, 256, 625, 1296]

print(list4) #[1, 4, 9]

2. 集合推导式

set1 = {1,2,3,4,5,6}

set2 = {i + i for i in set1}

set3 = {i**4 for i in set1}

##有选择行的筛选一下

set4 = {i*i for i in set1 if i < 4} ##小于4的再做转换 1 2 3

print(set1) #{1, 2, 3, 4, 5, 6}

print(set2) #{2, 4, 6, 8, 10, 12}

print(set3) #{256, 1, 16, 625, 81, 1296} 无序

print(set4) #{1, 4, 9}

3.字典推导式

dict_ = {

"韩欢": 18,

"西萌": 26,

"秀儿": 5

}

##拿出所有的key,并变成列表

dict_key = [key + "zzz" for key, value in dict_.items()]

##key和value颠倒

dict_s1 = {value: key for key, value in dict_.items()}

##只拿出符合条件的键值

dict_s2 = {key: value for key, value in dict_.items() if key == "韩欢"}

print(dict_key) #['韩欢zzz', '西萌zzz', '秀儿zzz']

print(dict_s1) #{18: '韩欢', 26: '西萌', 5: '秀儿'}

print(dict_s2) #{'韩欢': 18}

六、闭包

返回值是函数的函数

import time

def run_time():

def now_time():

print(time.time())

return now_time

f = run_time()

print(f()) ##当前时间戳

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值