• python基础---->python的使用(五)


      这里记录一些python的一些基础知识,主要内容是高阶函数的使用。或许我的心包有一层硬壳,能破壳而入的东西是极其有限的。所以我才不能对人一往情深。

    python中的高阶函数

    一、map()、reduce()和filter()函数使用

       map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。

    def f(x):
        return x * x
    print(list(map(f, range(1, 7)))) # [1, 4, 9, 16, 25, 36]
    
    print(list(map(lambda x: x * x, range(1, 7)))) # [1, 4, 9, 16, 25, 36]

       reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算。

    from functools import reduce
    def add(x, y):
        return x + y
    print(reduce(add, range(1, 10))) # 45
    
    print(reduce(lambda x, y: x + y, range(1, 10))) # 45

       filter()函数用于过滤序列。

    def is_odd(n):
        return n % 2 == 0
    print(list(filter(is_odd, range(1, 10)))) # [2, 4, 6, 8]
    
    print(list(filter(lambda x: x % 2 == 0, range(1, 10)))) # [2, 4, 6, 8]

      sorted()函数用于排序。

    def ownSort(n):
        return str(abs(n))[0]
    
    sortList = [-3, 9, -7, 10]
    print(sorted(sortList)) # [-7, -3, 9, 10]
    print(sorted(sortList, key=abs)) # [-3, -7, 9, 10]
    print(sorted(sortList, key=abs, reverse=True)) # [10, 9, -7, -3]
    print(sorted(sortList, key=ownSort)) # [10, -3, -7, 9]

    二、关于python变量的作用域理解

    def scope_test():
        def do_local():
            spam = "local spam"
    
        def do_nonlocal():
            nonlocal spam
            spam = "nonlocal spam"
    
        def do_global():
            global spam
            spam = "global spam"
    
        spam = "test spam"
        do_local()
        print("After local assignment:", spam)
        do_nonlocal()
        print("After nonlocal assignment:", spam)
        do_global()
        print("After global assignment:", spam)
        
    scope_test()
    print("In global scope:", spam)
    
    # After local assignment: test spam
    # After nonlocal assignment: nonlocal spam
    # After global assignment: nonlocal spam
    # In global scope: global spam

      Note how the local assignment (which is default) didn’t change scope_test’s binding of spam. The nonlocal assignment changed scope_test’s binding of spam, and the global assignment changed the module-level binding.

    三、python中协程的一个案例

    import asyncio
    import random
    import threading
    
    async def Hello(index):
        print('Hello world! index=%s, thread=%s' % (index, threading.currentThread()))
        await asyncio.sleep(random.randint(1, 5))
        print('Hello again! index=%s, thread=%s' % (index, threading.currentThread()))
    
    loop = asyncio.get_event_loop()
    tasks = [Hello(1), Hello(2)]
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()

    运行的结果如下:

    Hello world! index=2, thread=<_MainThread(MainThread, started 37900)>
    Hello world! index=1, thread=<_MainThread(MainThread, started 37900)>
    Hello again! index=1, thread=<_MainThread(MainThread, started 37900)>
    Hello again! index=2, thread=<_MainThread(MainThread, started 37900)>

    四、python中的base64编码与解码

    import base64
    # base64编码
    m = base64.b64encode(b'my name is huhx.')
    print(m) # b'bXkgbmFtZSBpcyBodWh4Lg=='
    
    # # base64解码
    bytes = base64.b64decode(m)
    print(bytes) # b'my name is huhx.'

    codecs模块的简单使用

    print('中国'.encode('utf-8')) # b'xe4xb8xadxe5x9bxbd'
    print('中国'.encode('gbk')) # b'xd6xd0xb9xfa'
    
    import codecs
    print(codecs.encode('中国', 'utf-8')) # b'xe4xb8xadxe5x9bxbd'
    print(codecs.encode('中国', 'gbk')) # b'xd6xd0xb9xfa'

    str对象的encode方法的文档如下:

    def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
        """
        S.encode(encoding='utf-8', errors='strict') -> bytes
        
        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        return b""

    友情链接

  • 相关阅读:
    如何在Windows下安装sass和compass
    HTTP 请求头中的 X-Forwarded-For
    HTTP 代理原理及实现
    node.js使用经验记录
    完美方案——iOS的WebView自适应内容高度
    购物车商品加减效果
    C++17新特性
    栈实现迷宫求解(c++版)
    二叉树遍历及实现
    经典乱码“烫烫烫”和“屯屯屯”
  • 原文地址:https://www.cnblogs.com/huhx/p/baseuselearnpython5.html
Copyright © 2020-2023  润新知