Python入门——Day5(内嵌函数,闭包,lambda表达式,两个牛逼的bif——filter,map)

内嵌函数(嵌套函数)

>>> def fun1():
	x = 5
	def fun2():
		x *= x
		return x
	return fun2()

>>> fun1()
# 报错:
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    fun1()
  File "<pyshell#13>", line 6, in fun1
    return fun2()
  File "<pyshell#13>", line 4, in fun2
    x *= x
UnboundLocalError: local variable 'x' referenced before assignment

这里x是局部变量,在fun2中不能被调用,可以用nonlocal语句解决。

>>> def fun1():
	x = 5
	def fun2():
		nonlocal x #这里说明x不是局部变量
		x *= x
		return x
	return fun2()

>>> fun1()
25

lambda表达式的作用(定义默认函数)

  • Python写一些执行脚本是,使用lambda就可以省下定义函数过程,比如说我们只是需要写两个简单的脚本来管理服务器时间,我们就不需要专门定义一个函数然后再写调用,使用lambda就可以是代码更加精简。
  • 对于一些比较抽象并且整个过程执行下来只需要调用一两次的函数,有时候给函数起名字也是很头疼的问题,但是使用lambda之后就不用考虑命名的问题了。
  • 简化代码的可读性,由于普通的屌丝函数阅读经常要跳到开头def定义部分,是用lambda函数就可以省去这样的步骤。
>>> def ds(x):
	return 2 * x + 1

>>> ds(5)
11
>>> g = lambda x : 2 * x + 1
>>> g(5)
1

>>> def add(x,y):
	return x + y

>>> add(1,2)
3
>>> g = lambda x,y: x + y
>>> g(1,2)
3

过滤器——filter

首先,可以查看filter的用法。

>>> help(filter)
Help on class filter in module builtins:

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.

可以看到,filter有两个参数:
filter(function or None, iterable) --> filter object
function 函数(None)和 iterable(迭代器)
我们用下面的例子来解释:

>>> filter(None,[1, 0, True, False])
<filter object at 0x0000027C0461AA90>
>>> list(filter(None,[1,0,True,False]))
[1, True]

>>> def okc(x):
	return x % 2

>>> temp = range(10)
>>> show = filter(okc,temp)
>>> show
<filter object at 0x0000027C04601070>
>>> list(show)#转化位list形式输出
[1, 3, 5, 7, 9]
一句话输出10以内的奇数
>>> list(filter(lambda x : x % 2 , range(10)))
[1, 3, 5, 7, 9]

map()——映射

  • map() 会根据提供的函数对指定序列做映射。第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
  • 语法与相关用法:
map(function,iterable,...) #语法

#列表输出10以内的3倍的数
>>> list(map(lambda x: x * 3 , range(10)))
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

>>>def square(x) :            # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
 
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]
发布了23 篇原创文章 · 获赞 14 · 访问量 713

猜你喜欢

转载自blog.csdn.net/weixin_45253216/article/details/104544949