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‘\xe4\xb8\xad\xe5\x9b\xbd‘
print(‘中国‘.encode(‘gbk‘)) # b‘\xd6\xd0\xb9\xfa‘

import codecs
print(codecs.encode(‘中国‘, ‘utf-8‘)) # b‘\xe4\xb8\xad\xe5\x9b\xbd‘
print(codecs.encode(‘中国‘, ‘gbk‘)) # b‘\xd6\xd0\xb9\xfa‘

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""

友情链接

时间: 2024-08-05 07:44:36

python基础---->python的使用(五)的相关文章

Python基础-Python流程控制

上篇文章 Python基础-基础使用 我们已经知道了Python解释器,Python的变量.和Python的输入输出.Python的注释和字符集,这篇文章,我们主要讲Python的流程控制 本文防盗链:http://python789.blog.51cto.com Python基础-Python流程控制 1.条件判断 1.1.if基本使用 if就是一个条件判断的,当满足不同样的条件的时候执行不同的操作,如法如下: if 条件1:     满足条件1 代码框 elif 添加2:     满足条件2

Python基础教程(第五章 条件、循环和其他语句)

本文内容全部出自<Python基础教程>第二版,在此分享自己的学习之路. ______欢迎转载:http://www.cnblogs.com/Marlowes/p/5329066.html______ Created on Xu Hoo 读者学到这里估计都有点不耐烦了.好吧,这些数据结构什么的看起来都挺好,但还是没法用它们做什么事,对吧? 下面开始,进度会慢慢加快.前面已经介绍过了几种基本语句(print语句.import语句.赋值语句).在深入介绍条件语句和循环语句之前,我们先来看看这几种基

Python基础学习笔记(五)常用字符串内建函数

参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-strings.html 3. http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000 Python字符串内建函数同样支持Unicode,常用函数如下表: 方法 描述 string.capitalize() 把字符串的第一个字符大写 string.center(wi

python基础----&gt;python的使用(三)

今天是2017-05-03,这里记录一些python的基础使用方法.世上存在着不能流泪的悲哀,这种悲哀无法向人解释,即使解释人家也不会理解.它永远一成不变,如无风夜晚的雪花静静沉积在心底. Python的基础学习 一.python中函数作为参数 import math def add(x, y, f): return f(x) + f(y) print(add(25, 9, math.sqrt)) # 8.0 二.python引用自定义模块 在同目录下面定义两个文件huhx.py和huhx5.p

重学Python - Day 05 - python基础 -&gt; python的文件操作:r、w、a、r+、a+ 、readline、readlines 、flush等常用的文件方法

文件的读操作 示例: 1 print("->文件句柄的获取,读操作:") 2 3 f = open('无题','r',encoding='utf8') 4 d = f.read() 5 f.close() 6 print(d) 7 8 print('->例二:') 9 f = open('无题','r',encoding='utf8') 10 e = f.read(9) 11 f.close() 12 print(e) 13 #python3中,文件中一个中英文都占位1 运

重学Python - Day 01 - python基础 -&gt; python版本选择+第一个小程序

题外话: Python版本:最新的3.6 安装注意点:勾选添加路径后自定义安装到硬盘的一级目录,例如本人的安装路径: F:\Python 原因:可以自动添加python环境变量,自动关联.py文件,其余的优点很多,例如学习selenium的,使用pip install selenium命令就可以安装selenium 3了,虽然python webdriver的自动化还是2.7居多,但是3.0会是未来 闲言碎语以后再说,现在正式开始学习Python,没办法,不会编程的测试在工作中好吃力,学不会py

Python基础篇【第五篇】:sed和函数

sed是一个无序且不重复的元素集合 1 class set(object): 2 """ 3 set() -> new empty set object 4 set(iterable) -> new set object 5 6 Build an unordered collection of unique elements. 7 """ 8 def add(self, *args, **kwargs): # real signatu

Python基础学习笔记(五)

本节继续完善第二节的数字小游戏: 1)继续使用 条件分支语句,以完善用户猜错数字时,给予提示,是猜大了还是小了: 2)使用 循环语句(while循环)以实现在不退出游戏的情况下,让用户多次猜数字,改善用户体验效果: 3)引入外援(import),导入外部模块,以实现更强大的功能,这里是使用随机数模块 random . 下面是游戏的代码: 本节需要注意的知识点: 1.python的语法是冒号和缩进,if分支结构和while循环结构的条件语句后面一定得有 : ,python中的命令区块时通过缩进实现

Python基础教程系列:五、序列

列表也是序列的一种,所以对于列表的操作同样适用于列表.也可以通过下标或者切片操作来访问某一个或者某个子列表.那么列表和字符串有什么区别呢?首先字符串必须只能由字符组成,即便字符串中有数字,那也是字符类型的数字,不可直接用于数学计算,其次,字符串中的字符具有不可变性.但是列表是可以保留任意数目的Python对象的灵活容器,就像一个大箱子,什么对象都可以往里放.列表具有元素可变性,在序列中,列表是唯一一种支持元素可变性的数据结构.列表在形式上类似于C.Java中的数组,但与数组还是有很大区别的.数组