angrykola

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
def 是可执行的代码,创建了一个对象并将其赋值给某一变量名
lambda 创建一个对象但将其作为结果返回
return 将一个结果对象发送给调用者
yield 向调用者发回一个结果对象,但是记住他离开的地方
global 声明了一个模块级的变量并且赋值
nonlocal 声明了将要赋值的一个封闭的函数变量

 

 

 

 

 

 

  • map函数
  • filter函数
  • reduce函数
  • 递归函数

lambda表达式,匿名函数

>>> x = lambda x,y:x*y
>>> x(8,9)
72

global与nonlocal

>>> def test(x):
        state = x
            def test1(y):
                nonlocal state  #声明局部变量
                print('x:',state,',y:',y)
                state += 1
            return test1
>>> test(0)
<function test.<locals>.test1 at 0x0000000003699048>
>>> x=test(0)
>>> x(0)
x: 0 ,y: 0
>>> x(1)
x: 1 ,y: 1
>>> x(100)
x: 2 ,y: 100

任意参数的实例

>>> def f(a,*args):
      print('a:',a,'arg:',args)    
>>> f(1,'a','v')
a: 1 arg: ('a', 'v')

>>> def test(**args):
      print(args)    
>>> test(a=1,b=2)
{'b': 2, 'a': 1}

>>> def t(*a,**ar):
      print(a)
      print(ar)
>>> t(1,2,3,a=1,b=2)
(1, 2, 3)
{'b': 2, 'a': 1}

 

关于函数设计:
耦合性:对于输入使用参数并且输出使用rerun语句;只有在真正必要的情况下使用全局变量;不要改变可变类型的参数,除非调用者希望这样做。
聚合性:每一个函数都应该又一个单一的、统一的目标。

递归函数:

>>> l=[1,2,3,4,5,6]
>>> def mysum(L):
      print(L)
        if not L:
            return 0
        else:
          return L[0] + mysum(L[1:])
>>> mysum(l)
[1, 2, 3, 4, 5, 6]
[2, 3, 4, 5, 6]
[3, 4, 5, 6]
[4, 5, 6]
[5, 6]
[6]
[]
21

 

注意:不要让你的代码变的晦涩难懂

if a:
    b
else
    c
#等价于
b if a else c

 

map函数:

map函数会对一个序列对象中的每一个元素应用被传入的函数,并且返回一个包含了所有函数调用结果的一个列表。

>>> def multiplication(x):return x * 10
>>> L = [1,2,3,4,5]
>>> L_update = list(map(multiplication,L))
>>> L_update
[10, 20, 30, 40, 50]
>>> list(map(lambda x:x+10 ,L))
[11, 12, 13, 14, 15]

 

 filter和reduce函数:

#filter过滤器
>>> l1=list(range(-10,10))  #首先新建一个列表l1
>>> l1
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l2=list(filter((lambda x:x>0),l1)) #设置一个过滤器规则建立列表l2
>>> l2
[1, 2, 3, 4, 5, 6, 7, 8, 9]

reduce在python2.6中只是一个简单的内置函数,但是在python3.0中则位于functool模块中,要复杂一些。

posted on 2013-11-07 17:19  kolaman  阅读(179)  评论(0)    收藏  举报