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

时间:2021-05-22

切片

从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转listlist(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) # 0next(g) # 1next(g) # 4for 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() # 获得可迭代对象callnext(call) # 0next(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]) # 返回Iteratorlist(i) # [1, 4, 9]
  • reduce
from functools import reducereduce(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 sumfn = lazy_sum(1, 2, 3) # ax + sum构成了闭包fn() # 6fn() # 12

匿名函数

即lambda表达式。

装饰器

函数包函数的语法糖?

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

偏函数

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

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

总结

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章