python 函数相关

0.lambda 不支持多行

参见:https://www.zhihu.com/question/22819202/answer/22746682

1.python lambda 简单的例子(map,filter,reduce )

转自:https://www.cnblogs.com/AlwaysWIN/p/6202320.html

from functools import reduce
foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]

print (list(filter(lambda x: x % 3 == 0, foo)))
#[18, 9, 24, 12, 27]

print (list(map(lambda x: x * 2 + 10, foo)))
#[14, 46, 28, 54, 44, 58, 26, 34, 64]

print (reduce(lambda x, y: x + y, foo))
#139

2.curry

不知道是不是就是这个样子,懒得深究了

#currying

fun3=lambda a,b,c:[a,b,c]
fun2=lambda a,b:fun3(a,b,3)
fun1=lambda a:fun2(a,2)
fun0=lambda :fun1(1)
print(fun0())#[1,2,3]

funx=lambda x: lambda y: lambda z:[x,y,z]
print(funx(1)(2)(3))#[1,2,3]

3.闭包

就是函数(或者lambda)在定义时把当前的环境变量打包,在该函数调用处,使用的变量是从这些打包的东西中查找的
闭包的概念可以参考:
http://www.yinwang.org/blog-cn/2012/08/01/interpreter
感觉王垠这篇的思考题的答案大概是,let [x,123] 这种在定义变量时,没有使用 除了x外的其他变量,但是如果是 let [x,lambda …]就依然会有domain的问题

闭包的两个条件:

  • 函数可以作为变量
  • 嵌套定义的函数

其实感觉,闭包相当于只有一个public成员的类。或者完全可以用只有单个public成员的类去模拟闭包。外层函数放到构造函数中,闭包的环境相当于类的private的 数据成员。那个public 可以是个函数指针(可以在构造函数用其他成员函数赋值),或者就是个普通的成员函数。

闭包的例子

x=1
def get_fun():
    global x
    x=2
    def fun():
        print(x)
    return fun
f=get_fun()
f() # output:2
x=3
f() # output:3

def get_fun1():
    #global x
    x=2
    def fun():
        nonlocal x # 注意nonlocal 关键字
        x=3
        print(x)
    return fun
f=get_fun1()
x=4
f() # output:3


def get_fun2(x):
	def fun():
		nonlocal x
		print(x)
	return fun
f1=get_fun2(1)
f2=get_fun2(2)
f1() # output:1
f2() # output:2

x=0
def get_fun3():
	global x
	x += 1
	def fun():
		print(x)
	return fun
f1=get_fun3()
f2=get_fun3()
f1() # output:2
f2() # output:2

参考:https://www.cnblogs.com/JohnABC/p/4076855.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值