这里记录一些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))) # print(reduce(lambda x, y: x + y, range(1, 10))) #

   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=, thread=<_MainThread(MainThread, started )>
Hello world! index=, thread=<_MainThread(MainThread, started )>
Hello again! index=, thread=<_MainThread(MainThread, started )>
Hello again! index=, thread=<_MainThread(MainThread, started )>

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

友情链接

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

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

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-strings.html 3. http://www.liaoxu ...

  2. python基础整理笔记(五)

    一. python中正则表达式的一些查漏补缺 1.  给括号里分组的表达式加上别名:以便之后通过groupdict方法来方便地获取. 2.  将之前取名为"name"的分组所获得的 ...

  3. python基础---->python的使用(三)

    今天是2017-05-03,这里记录一些python的基础使用方法.世上存在着不能流泪的悲哀,这种悲哀无法向人解释,即使解释人家也不会理解.它永远一成不变,如无风夜晚的雪花静静沉积在心底. Pytho ...

  4. Python基础--Python简介和入门

    ☞写在前面 在说Python之前,我想先说一下自己为什么要学Python,我本人之前也了解过Python,但没有深入学习.之前接触的语言都是Java,也写过一些Java自动化用例,对Java语言只能说 ...

  5. python基础-python解释器多版本共存-变量-常量

    一.编程语言的发展史 机器语言-->汇编语言-->高级语言,学习难度及执行效率由高到低,开发效率由低到高 机器语言:二进制编程,0101 汇编语言:用英文字符来代替0101编程 高级语言: ...

  6. python基础--python基本知识、七大数据类型等

    在此申明一下,博客参照了https://www.cnblogs.com/jin-xin/,自己做了部分的改动 (1)python应用领域 目前Python主要应用领域: 云计算: 云计算最火的语言, ...

  7. Python基础学习参考(五):字符串和编码

     一.字符串 前面已经介绍过字符串,通过单引号或者双引号表示的一种数据类型.下面就再来进一步的细说一下字符串.字符串是不可变的,当你定义好以后就不能改变它了,可以进一步的说,字符串是一种特殊的元组,元 ...

  8. Py修行路 python基础 (二十五)线程与进程

    操作系统是用户和硬件沟通的桥梁 操作系统,位于底层硬件与应用软件之间的一层 工作方式:向下管理硬件,向上提供接口 操作系统进行切换操作: 把CPU的使用权切换给不同的进程. 1.出现IO操作 2.固定 ...

  9. Python基础-python流程控制之循环结构(五)

    循环结构 循环结构可以减少源程序重复书写的代码量,用来描述重复执行某段算法的问题. Python中循环结构分为两类,分别是 while 和 for .. in. 一.while循环 格式1: whil ...

随机推荐

  1. 通配符的匹配很全面, 但无法找到元素 'context:property-placeholder'

    解决方案就是如下: xmlns:context="http://www.springframework.org/schema/context" 同时在xsi:schemaLocat ...

  2. Windows 环境搭建Redis集群(win 64位)

    转: http://blog.csdn.net/zsg88/article/details/73715947 参考:https://www.cnblogs.com/tommy-huang/p/6240 ...

  3. 【转】Gulp入门基础教程

    Gulp入门基础教程 原文在此 前言最近流行前端构建工具,苦于之前使用Grunt,代码很难阅读,现在出了Gulp, 真是摆脱了痛苦.发现了一篇很好的Gulp英文教程,整理翻译给大家看看. 为什么使用G ...

  4. thinkphp并发 阻塞模式与非阻塞模式

    结构代码 public function index(){ $fp = fopen("lock.txt", "w+"); if(flock($fp,LOCK_E ...

  5. 【项目管理】Project使用

    http://www.cnblogs.com/wangfupeng1988/p/3647166.html

  6. 通过expect免自动输入密码登陆远程服务器

    通过expect免自动输入密码登陆远程服务器 1.前提必须已经安装expect 2.新建login.sh,文件内容如下 #!/usr/bin/expect -f spawn ssh root@140. ...

  7. koa2使用阿里云oss的nodejs sdk实现上传图片

    nodejs实现上传图片到阿里云,自然是写成接口形式比较方便,前端监听input file的改变,把file对象传入到formData中传入后端,不能直接传入file对象,后端需要接受formData ...

  8. python中的List 和 Tuple

    #-*- coding:UTF-8 -*- classmates=["Michael","Bob","Tracy"] print(class ...

  9. Sublime的Package Control安装方法

    Package Control插件本身是一个为了方便管理插件的插件 最简单的方式是通过Sublime Text 3的console命令界面进行安装 Sublime text3 import urlli ...

  10. linux 中搜索命令的对比

    1.find find是最常用和最强大的查找命令.它能做到实时查找,精确查找,但速度慢. find的使用格式如下: #find [指定目录] [指定条件] [指定动作] 指定目录:是指所要搜索的目录和 ...