<潭州教育>-Python学习笔记7@python 内置函数,作用域,闭包,递归

1:常见的内置函数:
 
In [10]: dir(__builtins__).  # 查看内置函数
Out[10]:
['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'BlockingIOError',
'BrokenPipeError',
'BufferError',
'BytesWarning',
'ChildProcessError',
 
In [5]: len(dir(__builtins__))   ##一共有152个内置函数
Out[5]: 152
ArithmeticError AssertionError AttributeError BaseException BlockingIOError BrokenPipeError BufferError BytesWarning ChildProcessError ConnectionAbortedError ConnectionError ConnectionRefusedError ConnectionResetError DeprecationWarning EOFError Ellipsis EnvironmentError Exception False FileExistsError FileNotFoundError FloatingPointError FutureWarning GeneratorExit IOError ImportError ImportWarning IndentationError IndexError InterruptedError IsADirectoryError KeyError KeyboardInterrupt LookupError MemoryError ModuleNotFoundError NameError None NotADirectoryError NotImplemented NotImplementedError OSError OverflowError PendingDeprecationWarning PermissionError ProcessLookupError RecursionError ReferenceError ResourceWarning RuntimeError RuntimeWarning StopAsyncIteration StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TimeoutError True TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning ZeroDivisionError __IPYTHON__ __build_class__ __debug__ __doc__ __import__ __loader__ __name__ __package__ __spec__ abs all any ascii bin bool bytearray bytes callable chr classmethod compile complex copyright credits delattr dict dir display divmod enumerate eval exec filter float format frozenset get_ipython getattr globals hasattr hash help hex id input int isinstance issubclass iter len license list locals map max memoryview min next object oct open ord pow print property range repr reversed round set setattr slice sorted staticmethod str sum super tuple type vars zip
 
1.1 abs() ##求绝对值
In [12]: abs(100)
Out[12]: 100
 
1.2 len() ##求容器内长度
len(obj, /)
    Return the number of items in a container.
 
1.3 min(). ##最小值,输入一个可迭代对象
In [18]: min([1,2,3,4])
Out[18]: 1
 
1.4 max() ## 最大值 。输入一个可迭代对象
In [19]: dit = {'name':'Stone','age':23,'work':'yes'}
In [20]: max(dit)
Out[20]: ‘work’.    ###返回的最大值应该是按照字典的键的首字母的ascii码来排序
 
1.5  sorted()  #按照ASCII码排序
 
sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
 
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.
(END)
 
In [26]: sorted([1,2,3,4,3,2,5,6,1,2])
Out[26]: [1, 1, 2, 2, 2, 3, 3, 4, 5, 6]
 
1.6 reversed(). ##翻转
|  reversed(sequence) -> reverse iterator over values of the sequence
 
In [28]: reversed([1, 1, 2, 2, 2, 3, 3, 4, 5, 6])
Out[28]: <list_reverseiterator at 0x1063483c8>
 
In [29]: list(reversed([1, 1, 2, 2, 2, 3, 3, 4, 5, 6]))
Out[29]: [6, 5, 4, 3, 3, 2, 2, 2, 1, 1]
 
1.7 sum() ##求和
 
In [34]: sum([1,2,3],3)
Out[34]: 9
 
In [35]: sum([1,2,3])
Out[35]: 6
 
1.8 bin() ##转化成2进制
 
In [37]: bin(10)
Out[37]: '0b1010'
 
In [38]: bin(-199)
Out[38]: '-0b11000111'
 
In [39]: bin(-10)
Out[39]: '-0b1010'
 
1.9 oct() ##转化成8进制
    Return the Unicode code point for a one-character string.
In [40]: oct(10)
Out[40]: '0o12'
 
 
1.10 hex() #转化成16进制
    Return the hexadecimal representation of an integer.
 
    >>> hex(12648430)
    '0xc0ffee'
In [41]: hex(122)
Out[41]: '0x7a'
 
1.11 ord().  ##转化成ASCII码
In [43]: ord('S')
Out[43]: 83
 
1.12  chr(). ##转化成字符
In [47]: chr(123)
Out[47]: '{'
 
In [48]: chr(65)
Out[48]: 'A'
 
2.补充几个内置函数
2.1、enumerate() 返回一个枚举对象 传参时放一个可迭代参数,返回一个枚举对象,
In [50]: enumerate([1,2,3,3,5,6])
Out[50]: <enumerate at 0x10633d5a0>
 
In [51]: list(enumerate([1,2,3,3,5,6]))
Out[51]: [(0, 1), (1, 2), (2, 3), (3, 3), (4, 5), (5, 6)]
 
可以自定义初始索引:
In [52]: list(enumerate([1,2,3,3,5,6],3)).  ## 索引从3开始
Out[52]: [(3, 1), (4, 2), (5, 3), (6, 3), (7, 5), (8, 6)]
 
可以转化成字典:
In [53]: dict(enumerate([1,2,3,3,5,6],3))
Out[53]: {3: 1, 4: 2, 5: 3, 6: 3, 7: 5, 8: 6}
 
可迭代对象是集合时
In [54]: dict(enumerate({1,2,3,4,6},5))
Out[54]: {5: 1, 6: 2, 7: 3, 8: 4, 9: 6}
 
2.2 filter过滤函数
 
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.
 
用来筛选,类似漏斗,传参时放入函数或者None,后面放入可迭代对象,结果返回一个过滤器对象,需要通过list/dict转化。
In [57]: filter(None,[1,2,3,4,5])  ##返回一个过滤器对象
Out[57]: <filter at 0x1062b73c8>
 
In [58]: list(filter(None,[1,2,3,4,5]))  ##过滤条件为空,返回原可迭代对象
Out[58]: [1, 2, 3, 4, 5]
 
In [59]: filter(lambda x : x > 4,[1,2,3,43,5,3,5,6,5])     ##给定一个过滤的函数或None当参数,过滤对象是一个可迭代对象
Out[59]: <filter at 0x1063c4668>
 
In [60]: list( filter(lambda x : x > 4,[1,2,3,43,5,3,5,6,5]))    
Out[60]: [43, 5, 5, 6, 5]
 
2.3、map 全体加工
    
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.
 
 
 
2.4、zip 匹配
 将一个个可迭代对象一一配对,返回一个zip对象,可输入多个可迭代对象
 
zip(iter1 [,iter2 [...]]) --> zip object
|
|  Return a zip object whose .__next__() method returns a tuple where
|  the i-th element comes from the i-th iterable argument.  The .__next__()
|  method continues until the shortest iterable in the argument sequence
|  is exhausted and then it raises StopIteration.
 
 
 
3、函数内变量的作用域:
 3.1、变量类型
    全局变量:变量在函数外部定义,该变量的作用域是全局
    局部变量:变量在函数内部定义,该变量的作用域是局部
 
 
In [62]: x = 2. ##全局变量,全局作用域
 
In [63]: def fun():
    ...:     y = 2   ## 局部变量,作用于函数内部
    ...:     print (x,y)
    ...:
 
In [64]: fun()
2 2
 
3.2、global
    试用情况:1、当在函数内部需要改变全局变量时,需要声明global 
            2、函数内的局部变量需要在函数外调用到时,需要声明global
情况1
x  = 1
def fun2():
    global x   ## 不声明就会报错,UnboundLocalError: local variable 'x' referenced before assignment
 
    x += 3
    y = 23
    print ('x的值是:',x)
    print ('y的值是:',y)
 
fun2()
 
情况2
x  = 1
def fun2():
    global x
    x += 3
    global  y    #必须声明,不声明就会报错,NameError: name 'y' is not defined
 
    y = 23
    print ('x的值是:',x)
    print ('y的值是:',y)
 
fun2()
print ('函数外调用y:',y)  #NameError: name 'y' is not defined
 
 
 
3.3、nonlocal 声明局部变量
        适用情况:当里层局部需要改变外层局部时,需要调用nonlocal函数
 
def fun1():
    q = 1
    print('局部变量',q) #输出局部外层q
    def  fun2():
        w=33
        nonlocal q   #局部内层想要改变局部外层q,必须声明q,不声明就报错,
        q+=1
        print('局部里层',w)   #输出局部里层w
        print('局部里层',q)    #输出的是改变了的q
    fun2()              #由于这是内嵌函数,需要执行的话必须调用
    print ('最后看结果:',q)   ##q已经变化
# UnboundLocalError: local variable 'q' referenced(提及,引用) before assignment(分配,调用)
 
fun1()
 
 
3,闭包
“闭包”的意思,望文知意,可以形象的把它理解为一个封闭的包裹,这个包裹就是一个函数,当然还有函数内部对应的逻辑,包裹里面的东西就是自由变量,自由变量可以在随着包裹到处游荡。当然还得有个前提,这个包裹是被创建出来的。
在通过Python的语言介绍一下,一个闭包就是你调用了一个函数A,这个函数A返回了一个函数B给你。这个返回的函数B就叫做闭包。你在调用函数A的时候传递的参数就是自由变量。
 
 
 
4、回调函数
回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。
def clean1(times):
    """
    就假装是扫地吧,这种函数命名方式,千万别学习
    :param times: 次数
    :return: None
    """
    print ('已完成扫地次数:', str(times))
 
 
def clean2(times):
    """
    默默的装作洗抽油烟机
    :param times: 次数
    :return: None
    """
    print ('已洗抽油烟机次数', str(times))
 
 
def call_clean(times, function_name):
    """
    这个很重要,这个就是家政公司的业务系统,要啥业务都得在这说
    这个是实现回调函数的核心
    :param times:次数
    :param function_name:回调函数名
    :return:调用的函数结果
    """
    return function_name(times)
 
if __name__ == '__main__':
    call_clean(100, clean2)  #  给我洗100次抽油烟机,好吧,很变态
 
 
5.递归函数(函数调用自身)
  例题1:已知第一个人10岁,然后每个人一次比前面一个人大两岁,问第五个人的岁数
 
def howold(n):
    if n == 1:
        return 10
    else:
        return howold(n-1)+2
n = 4
print ('第%s个人%s岁'%(n,howold(n)))
 
 
    例题2:求阶乘
 
def jiecheng(n):
    if n == 1:
        return 1
    else:
        return jiecheng(n-1)*n
 
print(jiecheng(4))
 
 
 
六、作业
  1. 定义一个函数,输入一个序列(序列元素是同种类型),判断序列是顺序还是逆序,顺序输出UP,逆序输出DOWN,否则输出None
 
      2. 写一个函数,对元组 tu = (9,8,3,2,6,4,5,7,1),进行从小到大的排序。最后返回tu
 
      3. 猴子第一天摘下N个桃子,当时就吃了一半,还不过瘾,就又多吃了一个。第二天又将剩下的桃子吃掉一半,又多吃了一个。以后每天都吃前一天剩下的一半零一个。
   到第10天在想吃的时候就剩一个桃子了,问第一天共摘下来多少个桃子?
 
def houzi(n):
    if n == 10:
        return 1
    else:
        return (houzi(n+1)+1)*2
 
print (houzi(1))
>>1534
 
 
 
共有
10
1
 
 
9
4
3
1
8
10
6
4
7
22
12
10
6
46
23
22
5
93
47
46
 
 
posted @ 2018-03-08 18:59  工厂小OP  阅读(315)  评论(0编辑  收藏  举报