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 ...
随机推荐
- Retrofit/OkHttp API接口加固技术实践(下)
作者/Tamic http://blog.csdn.net/sk719887916/article/details/65448628 imageMogr2/auto-orient/strip%7Cim ...
- 基于struts2的ajaxfileupload异步上传插件的使用
服务器端采用struts2来处理文件上传. 所需环境: jquery.js ajaxfileupload.js struts2所依赖的jar包 及struts2-json-plugin-2.1.8.1 ...
- C++ 中的constkeyword
为什么使用const?採用符号常量写出的代码更easy维护:指针经常是边读边移动,而不是边写边移动:很多函数參数是仅仅读不写的.const最常见用途是作为数组的界和switch分情况标号(也能够用枚举 ...
- http 断点续传
一.序 Hi,大家好,我是承香墨影! HTTP 协议在网络知识中占据了重要的地位,HTTP 协议最基础的就是请求和响应的报文,而报文又是由报文头(Header)和实体组成.大多数 HTTP 协议的使用 ...
- oauth 2.0转
原文:http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html OAuth是一个关于授权(authorization)的开放网络标准,在全世界得到广泛 ...
- Android 布局学习之——LinearLayout属性baselineAligned的作用及baseline
相信大家对LinearLayout已经相当熟悉,但你们是否了解它的属性baselineAligned呢? Android官方文档是这么描述的:
- json字符串使用注意问题
json本身是字符串,即 json字符串 js使用 要把 json字符串 转为 javascript对象 json字符串转为js对象的方法:jquery的parseJSON var str='[{& ...
- 将nosetests的echo结果保存到本地文件
nose是很好用的python 测试框架. 但是一直很纠结如何将结果保存到本地.采用nosetests -h查看相关的options,找到一个xunit的东西,似乎可以实现功能. 测试结果: 可见,已 ...
- Golang优秀开源项目汇总
https://blog.csdn.net/hackstoic/article/details/52008307
- ajax+json+Struts2实现list传递(转载)
一.首先需要下载JSON依赖的jar包.它主要是依赖如下: json-lib-2.2.2-jdk15 ezmorph-1.0.4 commons-logging-1.0.4 c ...