Python高级特性与几种函数的讲解


Posted in Python onMarch 08, 2019

切片

从list或tuple中取部分元素。

list = [1, 2, 3, 4]
list[0 : 3] # [1, 2, 3]
list[-2 : -1] # -1表示最后一个,[3, 4]
list[1 :: 2] # index = 1开始,每两个取一个[2, 4]
list[:] # 复制list,[1, 2, 3, 4]
# 针对tuple,切片同样适用

iterable、iterator

可迭代,迭代器,集合类型数据可迭代但不是迭代器,可通过iter()转变为迭代器。

可迭代对象可使用for-in语句遍历,判断x是否可迭代:isinstance(x, Iterable)。

列表生产式

高效创建列表,见代码示例:

# range转list
list(range(1, 5)) # [1, 2, 3, 4]
[x * x for x in range(1, 5)] # [1, 4, 9, 16]
[x * x for x in range(1, 5) if x % 2 == 0] # [4, 16]
[m + n for m in 'ABC' for n in 'XYZ'] # ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
[s.lower() for s in ['Hello', 'World', 'IBM', 'Apple']] # like map

generator

isinstance(generator, Iterable) = True,可使用for-in语句,或者使用next方法。

g = (x * x for x in range(10))
next(g) # 0
next(g) # 1
next(g) # 4
for item in g:
  print(item) # 9 16 ... 81

generator函数

generator函数本质是一个有状态的函数,遇到yield语句时会暂时返回。

# 有yield语句,表明时generator函数
def gen_fn():
  init = 0
  while init < 10:
    yield init
    init += 1
  return 'done'
call = gen_fn() # 获得可迭代对象call
next(call) # 0
next(call) # 1
# 每次调用generator函数,得到的是一个新的generator
# for-in无法获得generator的返回值'done'
for item in gen_fn():
  print(item) # 0 1 ... 9

高阶函数

参数是函数的函数即是高阶函数,可对比数学概念:g(x) = f(x) + 1,g(x)即高阶函数。

  • map
# map(func, *iterables, ...)
i = map(lambda x : x * x, [1, 2, 3]) # 返回Iterator
list(i) # [1, 4, 9]
  • reduce
from functools import reduce
reduce(lambda previous, x : previous + x, [1, 2, 3, 4]) # 10
  • filter
i = filter(lambda x : x % 2 == True, [1, 2, 3, 4])
list(i) # [1, 3]
  • sorted 默认升序,通过key参数决定排序规则。
sorted([1,3,2], key = lambda x : -x) # [3, 2, 1]

返回函数做回函数返回值

闭包概念:包含环境成分(自由变量)和控制成分的实体(lambda表达式,函数)。

def lazy_sum(*args):
  ax = 0
  def sum():
    nonlocal ax
    for n in args:
      ax = ax + n
    return ax
  return sum
fn = lazy_sum(1, 2, 3)  # ax + sum构成了闭包
fn() # 6
fn() # 12

匿名函数

即lambda表达式。

装饰器

函数包函数的语法糖?

def log(fn):
  def call(*args, **kw):
    print('call %s():' % fn.__name__)
    return fn(*args, **kw)
  return call
# @log的作用等同now = log(now)
@log
def now():
  print('2018-03-18')
now() # call now(): 2018-03-18

偏函数

把一个函数的某些参数给固定住,返回一个新的函数。类似柯里化,但更强大?

from functools import partial
binary_int = partial(int, base = 2)
binary_int('1000000') # 64

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对三水点靠木的支持。如果你想了解更多相关内容请查看下面相关链接

Python 相关文章推荐
Python获取服务器信息的最简单实现方法
Mar 05 Python
在Python中用keys()方法返回字典键的教程
May 21 Python
Python简单读取json文件功能示例
Nov 30 Python
Python用户推荐系统曼哈顿算法实现完整代码
Dec 01 Python
python编程实现随机生成多个椭圆实例代码
Jan 03 Python
详解python中的线程
Feb 10 Python
python3读取csv和xlsx文件的实例
Jun 22 Python
python简易实现任意位数的水仙花实例
Nov 13 Python
Python识别html主要文本框过程解析
Feb 18 Python
Pycharm Plugins加载失败问题解决方案
Nov 28 Python
python实现b站直播自动发送弹幕功能
Feb 20 Python
python实现控制台输出颜色
Mar 02 Python
Python I/O与进程的详细讲解
Mar 08 #Python
举例讲解Python常用模块
Mar 08 #Python
python re库的正则表达式入门学习教程
Mar 08 #Python
opencv与numpy的图像基本操作
Mar 08 #Python
Python脚本修改阿里云的访问控制列表的方法
Mar 08 #Python
python实现整数的二进制循环移位
Mar 08 #Python
Python3实现的反转单链表算法示例
Mar 08 #Python
You might like
php变量范围介绍
2012/10/15 PHP
如何阻止网站被恶意反向代理访问(防网站镜像)
2014/03/18 PHP
php格式化日期实例分析
2014/11/12 PHP
PHP使用gmdate实现将一个UNIX 时间格式化成GMT文本的方法
2015/03/19 PHP
如何通过View::first使用Laravel Blade的动态模板详解
2017/09/21 PHP
ThinkPHP6.0如何利用自定义验证规则规范的实现登陆
2020/12/16 PHP
基于jquery的一个拖拽到指定区域内的效果
2011/09/21 Javascript
Jquery异步请求数据实例代码
2011/12/28 Javascript
如何用jQuery实现ASP.NET GridView折叠伸展效果
2015/09/26 Javascript
JavaScript数组的一些奇葩行为
2016/01/25 Javascript
jQuery事件绑定on()与弹窗实现代码
2016/04/28 Javascript
详解js产生对象的3种基本方式(工厂模式,构造函数模式,原型模式)
2017/01/09 Javascript
原生js和css实现图片轮播效果
2017/02/07 Javascript
node.js 中间件express-session使用详解
2017/05/20 Javascript
Vue计算属性的使用
2017/08/04 Javascript
javascript数组拍平方法总结
2018/01/20 Javascript
JS中的回调函数实例浅析
2018/03/21 Javascript
完美解决linux下node.js全局模块找不到的情况
2018/05/16 Javascript
vuejs 动态添加input框的实例讲解
2018/08/24 Javascript
jQuery层叠选择器用法实例分析
2019/06/28 jQuery
layui2.0使用table+laypage实现真分页
2019/07/27 Javascript
python定时器使用示例分享
2014/02/16 Python
详解Python中open()函数指定文件打开方式的用法
2016/06/04 Python
使用python和pygame绘制繁花曲线的方法
2018/02/24 Python
python生成每日报表数据(Excel)并邮件发送的实例
2019/02/03 Python
对Pytorch中Tensor的各种池化操作解析
2020/01/03 Python
flask利用flask-wtf验证上传的文件的方法
2020/01/17 Python
南非领先的在线旅行社:Travelstart南非
2016/09/04 全球购物
网络工程师面试(三木通信技术有限公司)
2013/06/05 面试题
护士岗前培训自我评鉴
2014/02/28 职场文书
文体活动实施方案
2014/03/27 职场文书
企业年检委托书范本
2014/10/14 职场文书
限期整改通知书
2015/04/22 职场文书
陈斌强事迹观后感
2015/06/17 职场文书
公司仓库管理制度
2015/08/04 职场文书
详解Mysql事务并发(脏读、不可重复读、幻读)
2022/04/29 MySQL