首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python基础-内置函数-作用域-闭包

python基础-内置函数-作用域-闭包

作者头像
py3study
发布2020-01-03 17:56:36
4310
发布2020-01-03 17:56:36
举报
文章被收录于专栏:python3python3

内置函数-作用域-闭包-递归

1.几个可能用到的内置函数

查看内置函数:
    print(dir(__builtins__))
常见函数:
    len 求长度
    min 最小值
    max 最大值
    sorted 排序,从小到大
    reversed 反向
    sum 求和
进制转换:
    bin()  转换为二进制
    oct()   转换为八进制
    hex()   转换为十六进制
    ord()   将字符转换成对应的ASIIC码值
    chr()   将ASIIC码值转换成对应的字符
补充:
    1.enumerate()   返回一个可以枚举的对象
    2.filter()      过滤器
    3.map()         加工。对于参数iterable中的每个元素都应用fuction函数,并返回一个map对象
    4.zip()         将对象逐一配对

1.1 查看参数使用:
    >>> help(sum)
Help on built-in function sum in module builtins:
sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

  >>> sum((1,23,4))
  28
  >>> sum([1,2,3])
  6
  >>> sum([1,2,3],10)
  16
  >>> sum([10,20,30],20)  #值=iterable值+start值
  80
  >>> sum([10,20,30],22)    #值=iterable值+start值
  82
  >>> sum({1:12,2:30})      #key相加 
  3
1.2 二进制:
  >>> bin(1)
  '0b1'
  >>> bin(2)
  '0b10'
1.3 八进制:
  >>> oct(8)
  '0o10'
  >>> oct(12)
  '0o14'
1.4 十六进制:
  >>> hex(10)
  '0xa'
  >>> hex(9)
  '0x9'
  >>> hex(15)
  '0xf'
1.5 将ASIIC码转换成相应的字符
  >>> chr(65)
  'A'
  >>> chr(32)
  ' '
1.6 将字符转换成ASIIC码
  >>> ord('a')
  97
  >>> ord(' ')
  32
1.7 enumerate:
    >>> help(enumerate)
    Help on class enumerate in module builtins:

    class enumerate(object)
     |  enumerate(iterable[, start]) -> iterator for index, value of iterable
     |  
     |  Return an enumerate object.  iterable must be another object that supports
     |  iteration.  The enumerate object yields pairs containing a count (from
     |  start, which defaults to zero) and a value yielded by the iterable argument.
     |  enumerate is useful for obtaining an indexed list:
     |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
     |  
     |  Methods defined here:
     |  
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |  
     |  __iter__(self, /)
     |      Implement iter(self).
     |  
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |  
     |  __next__(self, /)
     |      Implement next(self).
     |  
     |  __reduce__(...)
     |      Return state information for pickling.
  >>> enumerate([1,2,3,4])
  <enumerate object at 0x000000000343EF78>      #返回一个迭代器
  >>> list(enumerate([1,2,3,4]))                    #查看
  [(0, 1), (1, 2), (2, 3), (3, 4)]              #返回一个带索引的可枚举对象,index默认0,也可指定
  >>> list(enumerate(['a','b','c','d']))
  [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]      #返回一个带索引的可枚举对象,index默认0,也可指定
  >>> list(enumerate(['a','b','c','d'],3))
  [(3, 'a'), (4, 'b'), (5, 'c'), (6, 'd')]
  >>> list(enumerate((1,23,4,5,6),3))
  [(3, 1), (4, 23), (5, 4), (6, 5), (7, 6)]
  >>> list(enumerate({1,2,3,4,5},3))        #返回一个伪索引
  [(3, 1), (4, 2), (5, 3), (6, 4), (7, 5)]
  >>> list(enumerate({1:2,2:3,3:4},3))      #按可以返回
  [(3, 1), (4, 2), (5, 3)]
1.8 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). 
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |  __next__(self, /)
     |      Implement next(self).
     |  __reduce__(...)
     |      Return state information for pickling.
     >>> filter(lambda x:x>2,[1,2,3,4,5])   #lambda x:x>2是个函数体
    <filter object at 0x0000000003420EB8>   #返回函数体
    >>> list(filter(lambda x:x>2,[1,2,3,4,5]))
    [3, 4, 5]
    >>> list(filter(None,[1,2,3,4,5]))
    [1, 2, 3, 4, 5]
1.9 map加工
  >>> help(map)
  Help on class map in module builtins:
  class map(object)
   |  map(func, *iterables) --> map object
   |  Make an iterator that computes the function using arguments from
   |  each of the iterables.  Stops when the shortest iterable is exhausted.
   |  Methods defined here:
   |  __getattribute__(self, name, /)
   |      Return getattr(self, name).
   |  __iter__(self, /)
   |      Implement iter(self).
   |  __new__(*args, **kwargs) from builtins.type
   |      Create and return a new object.  See help(type) for accurate signature. 
   |  __next__(self, /)
   |      Implement next(self).
   |  __reduce__(...)
   |      Return state information for pickling.
   >>> list(map(str,[1,2,3,4]))
    ['1', '2', '3', '4']
1.10 zip 将对象逐一配对
    >>> list(zip([1,2,3],[4,5,6]))
    [(1, 4), (2, 5), (3, 6)]
    >>> list(zip((1,2,3),(4,5,6)))
    [(1, 4), (2, 5), (3, 6)]
    >>> list(zip([1,2,3],(4,5,6)))
    [(1, 4), (2, 5), (3, 6)]
    >>> list(zip([1,2,3,4],[5,6,7,8,9],['a','b']))
    [(1, 5, 'a'), (2, 6, 'b')]

2.函数内变量的作用域

变量的作用域与其定义的方式有关:
    局部变量:变量在函数内部定义,则变量的作用域在函数内部
    全局变量:变量在函数的外部定义,则变量的作用域是全局

    global:用来在函数或其它局部作用域中,声明全局变量.(作用于全局)
    nonlocal:用在函数或其它作用域中,声明外层(非全局)变量。(作用于局部)
使用global情况:
    全局变量可以在函数内部访问,但 不能改变
    如果在函数内部想修改全局变量,可以使用global来修饰变量

    局部变量只能在局部进行访问和修改
    如果在函数外部,想访问局部变量,也可以使用global,将局部变量声明为全局变量

使用nonlocal的情况:
    当里层局部,需要修改外层局部时,需要使用nonlocal。(如:嵌套函数)

总结:
    global: 函数中,需要修改全局变量时使用
    nonlocal:当里层局部,需要修改外层局部时,使用。(局部调用局部,使用nonlocal)

2.1 全局、局部变量
    x=1         #全局变量,全局能被局部引用,但不能被局部修改
    def fun():
        y=2     #局部变量不能进入全局
        print(x,y)
2.2 局部修改全局变量,使用global
    x=1
    def fun():
        global x   #先声明
        x += 1
        print(x)
2.3 全局调用局部变量,使用global
    def fun():
        global x
        x = 1
        print(x)
2.4 局部变量
    def test():
        a=1             #局部外层变量
        print(a)
        def test2():
            b=2         #局部里层变量
            print(a,b)
        test2()         #没有此行,只输出test()。test2()不输出
     >>> test()
      1
      1 2
  2.5 局部里层修改局部外层:
    def test():
      a=1       #局部外层
      print(a)
      def test2():
          b=2       #局部里层
          nonlocal a        #声明为局部变量
          a += 1            #修改变量
          print(a,b)
    test2()
    >>> test()
    1
    2 2

3.内嵌函数和闭包

嵌套函数:
  def test():
      a=1
      print(a)
      def test2():
          b=2
          nonlocal a
          a += 1
          print(a,b)
      test2()       #嵌套函数调用内嵌函数
 闭包<两个函数,嵌套>:
     def test():
        a=1
        print(a)
        def test2():
            b=2
            print(b)
        return test2    #返回里层函数的函数体-闭包
    >>> test()
    1
    <function test.<locals>.test2 at 0x00000000005B7F28>
回调函数<两个函数,不嵌套>:
    def test1():
        print('first')
    def fun(a):
        a()
        print('two')
    fun(test1)
    ================== RESTART: C:\Users\xinyu\Desktop\test.py ==================
    first
    two

4.递归

函数调用自己本身

'''
例题:有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。
       问第4个人岁数,他说比第3个人大2岁。
       问第三个人,又说比第2人大两岁。
       问第2个人,说比第一个人大两岁。
       最后问第一个人,他说是10岁。
       请问第五个人多少岁?
'''
递归的核心:
    1.递归推导式
    2.递归终止条件
def age(n):
    if n == 1:
        return 10
    else:
        return age(n-1)+2

阶乘: 5!=5*4*3*2*1
#n != n*(n-1)*(n-2)*....1
def jicheng(n):
    if n == 1:
        return 1
    else:
        return jicheng(n-1)*n
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档