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))) # 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的使用(五)的更多相关文章
- Python基础学习笔记(五)常用字符串内建函数
		
参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-strings.html 3. http://www.liaoxu ...
 - python基础整理笔记(五)
		
一. python中正则表达式的一些查漏补缺 1. 给括号里分组的表达式加上别名:以便之后通过groupdict方法来方便地获取. 2. 将之前取名为"name"的分组所获得的 ...
 - python基础---->python的使用(三)
		
今天是2017-05-03,这里记录一些python的基础使用方法.世上存在着不能流泪的悲哀,这种悲哀无法向人解释,即使解释人家也不会理解.它永远一成不变,如无风夜晚的雪花静静沉积在心底. Pytho ...
 - Python基础--Python简介和入门
		
☞写在前面 在说Python之前,我想先说一下自己为什么要学Python,我本人之前也了解过Python,但没有深入学习.之前接触的语言都是Java,也写过一些Java自动化用例,对Java语言只能说 ...
 - python基础-python解释器多版本共存-变量-常量
		
一.编程语言的发展史 机器语言-->汇编语言-->高级语言,学习难度及执行效率由高到低,开发效率由低到高 机器语言:二进制编程,0101 汇编语言:用英文字符来代替0101编程 高级语言: ...
 - python基础--python基本知识、七大数据类型等
		
在此申明一下,博客参照了https://www.cnblogs.com/jin-xin/,自己做了部分的改动 (1)python应用领域 目前Python主要应用领域: 云计算: 云计算最火的语言, ...
 - Python基础学习参考(五):字符串和编码
		
一.字符串 前面已经介绍过字符串,通过单引号或者双引号表示的一种数据类型.下面就再来进一步的细说一下字符串.字符串是不可变的,当你定义好以后就不能改变它了,可以进一步的说,字符串是一种特殊的元组,元 ...
 - Py修行路 python基础 (二十五)线程与进程
		
操作系统是用户和硬件沟通的桥梁 操作系统,位于底层硬件与应用软件之间的一层 工作方式:向下管理硬件,向上提供接口 操作系统进行切换操作: 把CPU的使用权切换给不同的进程. 1.出现IO操作 2.固定 ...
 - Python基础-python流程控制之循环结构(五)
		
循环结构 循环结构可以减少源程序重复书写的代码量,用来描述重复执行某段算法的问题. Python中循环结构分为两类,分别是 while 和 for .. in. 一.while循环 格式1: whil ...
 
随机推荐
- win32 数据类型 vs c#
			
在C#中做很多应用需要使用win32 API,但发现原型函数的一些数据类型看起来非常费劲,甚至在C#中“没有”这种数据类型,查阅了一下资料,数据类型对应关系整理如下,希望对大家有用: BOOL=Sys ...
 - (原)从mp4,flv文件中解析出h264和aac,送解码器解码失败
			
转载请注明出处:http://www.cnblogs.com/lihaiping/p/5285166.html 今天在做本地文件解码测试,发现从mp4,flv文件中读出来的帧数据,h264和aac帧直 ...
 - Erlang编程语言的一些痛点
			
Erlang编程语言的一些痛点 http://www.zhihu.com/question/34500981
 - Redis系列-php怎么通过redis扩展使用redis
			
From: http://blog.csdn.net/love__coder/article/details/8691679 通过前面几篇blog,我们应该对redis有个大致的认识,这里再讲解下,p ...
 - 通过 Service 访问 Pod
			
我们不应该期望 Kubernetes Pod 是健壮的,而是要假设 Pod 中的容器很可能因为各种原因发生故障而死掉.Deployment 等 controller 会通过动态创建和销毁 Pod 来保 ...
 - 自定义控件?试试300行代码实现QQ侧滑菜单
			
Android自定义控件并没有什么捷径可走,需要不断得模仿练习才能出师.这其中进行模仿练习的demo的选择是至关重要的,最优选择莫过于官方的控件了,但是官方控件动辄就是几千行代码往往可能容易让人望而却 ...
 - 编译并使用带有OpenCL模块的OpenCV for android SDK
			
OpenCV Android SDK中提供的静态.动态库是不支持OpenCL加速的,如果在程序中调用OpenCL相关函数,编译时不会报错,但运行时logcat会输出如下信息,提示OpenCL函数不可用 ...
 - jquery获取表单数据方法$.serializeArray()获取不到disabled的值
			
$.serializeArray()获取不到disabled的值 经实验,$.serializeArray()获取不到disabled的值,如果想要让input元素变为不可用,可以把input设为re ...
 - python,如何获取字符串中的子字符串,部分字符串
			
说明: 比如有一个字符串,python,如何就获取前3位,或者后2位.在此记录下. 操作过程: 1.通过分割符的方式,下标的方式,获取字符串中的子串 >>> text = 'pyth ...
 - Innodb表压缩过程中遇到的坑(innodb_file_format)
			
https://www.cnblogs.com/billyxp/p/3342969.html