Itertools

迭代器是一个对象,可以通过next函数形成一个序列,直到不能迭代为止。

用途:生成虚拟的序列;节省内存空间

import itertools
nums = itertools.count(0,2)
print(next(nums))
print(next(nums))
print(next(nums))"""
0
2
4
"""

利用for循环进行遍历:

import itertools
nums = itertools.count(0,2)
for i in nums:if i > 6:breakprint(i)"""
0
2
4
6
"""

cycle函数进行循环:

import itertools
cycle_strings = itertools.cycle('ABC')
i = 1
for string in cycle_strings:if i == 7:breakprint(string)i = i + 1"""
A
B
C
A
B
C
"""

repeat函数进行重复:

import itertools
for item in itertools.repeat('hello', 3):print(item)"""
hello
hello
hello
"""

Generators

yield返回值,相当于函数的暂停,当调用next时函数继续运行。

def yrange(n):i = 0while i < n:yield ii = i + 1
o = yrange(5)
print(next(o))
print(next(o))
print(next(o))
print(next(o))
print(next(o))
print(next(o))"""
0
1
2
3
4
Traceback (most recent call last):File "test.py", line 13, in <module>print(next(o))
StopIteration
"""

迭代器的简写方法:

g = (x * x for x in range(4))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))"""
0
1
4
9
Traceback (most recent call last):File "<stdin>", line 1, in <module>
StopIteration
"""

Map函数

map函数接收的第一个参数为一个函数对象,后面接收1个或多个序列;map函数会将func作用在后面序列中的各个值上,并返回一个迭代器。

def f(x):return x * x
y = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(y))"""
[1, 4, 9, 16, 25, 36, 49, 64, 81]
"""

Filter函数

filter()函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。

filter()接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

def k(x):return x%2 == 0
y = list(filter(k, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(y)"""
[2,4,6,8]
"""

Lambda匿名函数

lambda的主体是一个表达式,且自带返回,不需要return。lambda本身返回的是一个函数。

list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
"""
[1, 4, 9, 16, 25, 36, 49, 64, 81]
"""

快速生成列表

注意,[]得到列表,()得到迭代器

"""
[ expression for value in iterable if condition ]
"""[x * x for x in range(1, 11) if x % 2 == 0]
"""
[4, 16, 36, 64, 100]
"""[m + n for m in 'ABC' for n in 'XYZ']
"""
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
"""

Closure Function

对于函数中不确定的参数,可以通过闭包函数来传递参数从而得到一系列相似功能的函数。

def make_mul_of(n):def multiplier(x):return x*nreturn multiplier
time3 = make_mul_of(3)
time5 = make_mul_of(5)
print(time3(4))
print(time5(10))"""
12
50
"""

Decorator

装饰器不改变函数本身,可以在函数的前后执行一些函数,起到打包的作用。

def new_decorator(a_function_to_decorate):def the_wrapper():print("Before the function runs") a_function_to_decorate()print("After the function runs")return the_wrapperdef a_function():print("I am a stand alone function.")a_function_decorated = new_decorator(a_function)
a_function_decorated()"""
Before the function runs
I am a stand alone function.
After the function runs
"""

简便写法:在函数前加@decorator_name

@多个装饰器,离函数近的先执行,远的后执行。

def new_decorator(a_function_to_decorate):def the_wrapper():print("Before the function runs") a_function_to_decorate()print("After the function runs")return the_wrapper@new_decorator
def func():print("Leave me alone")func()"""
Before the function runs
Leave me alone
After the function runs
"""

传参时,要保证function_to_decorate中的参数与被装饰函数(function_with_no_argument)的参数不冲突。

def a_decorator_passing_arbitrary_arguments(function_to_decorate):def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):print("Do I have args?:")print(args);print(kwargs)function_to_decorate(*args, **kwargs)return a_wrapper_accepting_arbitrary_arguments@a_decorator_passing_arbitrary_arguments
def function_with_no_argument():print("Python is cool, no argument here.")function_with_no_argument()"""
Do I have args?:
()
{}
Python is cool, no argument here.
"""

9_Conveniences相关推荐

最新文章

  1. SSM实现大学生综合素质评测系统
  2. oracle查询表占用空,Oracle 表的行数、表占用空间大小,列的非空行数、列占用空间大小 查询...
  3. jq之$(“a[target=‘_blank‘]“)
  4. ZuulFilter的使用场景
  5. flask.Config(root_path, defaults=None)
  6. MapReduce :通过数据具有爷孙关系的结果
  7. java基础杂谈(一)
  8. Android8 for 9300,三星G9300官方固件rom刷机包 G9300ZCS3CRI1 安卓8.0
  9. java基于springboot+vue的学生宿舍报修管理系统(源码+数据库+Lw文档)
  10. r语言 col_co,cob,col,con,cor,cog前缀其实都是com变化而已
  11. android 自动调节音量,Android 音量调节
  12. 使用STM32F4浮点运算(FPU)功能开启+使用DSP库
  13. 张艾迪(创始人):拥抱单身与自由的Eidyzhang
  14. 记一次Rider手写UnityShader_非图解基本的光照模型,包含ViewDir_NdotL高光和漫反射等等计算
  15. Python数据类型变量命名format集合等
  16. 智能机器人无法智能对话_关于智能语音机器人使用中可能出现的问题
  17. 复式、别墅、大户型无线wifi覆盖方案
  18. android 播放视频结束回调,Android万能音频播放器09-添加Seek功能和完成播放回调...
  19. ApiCloud链接云端数据库
  20. 【camera】【CMOS Sensor】感光芯片cmos sensor简单介绍

热门文章

  1. Microsoft.AlphaImageLoader滤镜讲解
  2. XML文件解析(在Windows环境MFC程序中,使用自带的MSXML6.dll解析)
  3. python 进行一元线性回归并输出相关结果,Python 一元线性回归 - 树懒学堂
  4. PBOC标准流程 apdu交互指令
  5. 不同工作年限的员工离职原因
  6. WASM 原生时代已经到来 | 解读 WebAssembly 的 2022
  7. 转:WCAT 压力工具介绍
  8. Jetbrains系列产品重置试用方法
  9. 有哪些句子是真正写到你的心里去了?
  10. android 格式化为exfat,Android 4.2是否支持exfat格式U盘?如何使Android支持exfat