>>> def fun1():
x = 5
def fun2():
x *= x
return x
return fun2()
>>> fun1()
# 报错:
Traceback (most recent call last):
File "" , line 1, in <module>
fun1()
File "" , line 6, in fun1
return fun2()
File "" , 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
>>> 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的用法。
>>> 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(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]