介绍

Python3中实现了很多生成器函数,本篇主要介绍built-in、itertools、functools模块中的生成器。

过滤器生成器

本类生成器函数将iterable对象作为参数,在不改变该iterable对象的条件下,返回iterable子集的生成器对象。

filter(predicate, iterable)

iterable的每一个元素会传入predicate函数中判断是否为True,该生成器会返回所有返回为True的元素组成的生成器对象。

def is_vowel(c):return c.lower() in 'aeiou'word = 'abcdefghijk'
print(list(filter(is_vowel, word)))
## output: ['a', 'e', 'i']

filter会过滤掉word中所有非元音字母,返回符合元素组成的生成器对象。
注意:通过list(generator)可以将生成器对象转换为列表,但如果是无限生成器list将会产生大量元素导致出错。
filter函数等同于下面的生成器表达式用法。

(item for item in iterable if function(item))

如果filter的第一个参数为None,则不过滤返回全部,等同于下面的生成器表达式用法。

(item for item in iterable if item)

itertools.filterfalse(predicate, iterable)

该函数和filter类似,区别是过滤掉predicate返回True的元素。

print(list(itertools.filterfalse(is_vowel, word)))
## output: ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k']

itertools.takewhile(predicate, iterable)

该函数连续迭代iterable对象中的元素,并用predicate函数判断,若predicate返回为True,将不断产出该元素,直到predicate返回False,过滤了iterable后面不符合的元素。

print(list(itertools.takewhile(is_vowel, word)))
## output: ['a']

itertools.dropwhile(predicate, iterable)

该函数与itertools.takewhile相反,过滤了iterable对象前面符合predicate返回True的元素,保留后面的子集。

print(list(itertools.dropwhile(is_vowel, word)))
## output: ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']

itertools.compress(iterable, selectors)

该函数中的selectors也是一个迭代对象,compress根绝selectors中的值(0/1或是True/False)判断是否过滤iterable中的元素。

print(list(itertools.compress(word, [1, 0, 1, 0])))
## output: ['a', 'c']

如果selectors长度不够,则iterable后面的对象全部被过滤掉。

itertools.islice(iterable, stop)

根据传入参数的个数不同,该函数另一种写法是itertools.islice(iterable, start, stop[, step]),islice函数类似python中的分片操作:list[start:stop:step]。

print(list(itertools.islice(word, 4)))
## output: ['a', 'b', 'c', 'd']
print(list(itertools.islice(word, 4, 8)))
## output: ['e', 'f', 'g', 'h']
print(list(itertools.islice(word, 4, 8, 2)))
## output: ['e', 'g']

映射生成器

该类生成器主要对于传入的一个或多个迭代对象中的每一个元素进行操作,返回映射后的生成器对象。

map(func, *iterables, timeout=None, chunksize=1)

map是Python中常用的原生生成器,将迭代对象中的每一个元素传入func进行映射返回新的迭代对象。如果有n个iterable对象,则func的参数则为n个,后面的timeout和chunksize参数涉及到异步,本篇将不阐述。

print(list(map(lambda x: x.upper(), word)))
print([x.upper() for x in word])
## output: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']

上面第一行中的map将word中的每个元素转换为大写,和第二行中的列表生成式用法相似。

print(list(map(lambda x, y: (x, y), word, word)))
print(list(zip(word, word)))
## output: [('a', 'a'), ('b', 'b'), ('c', 'c') ... ('k', 'k')]

当有两个iterable传入时,func将需要处理传入的两个参数,第一行的用法和zip函数的作用相似。

itertools.starmap(function, iterable)

当iterable中的元素也是个迭代对象时,如果使用map函数,需要在函数内部实现解压操作获取到单个元素,而startmap将iterable中的元素按function(*item)方式传入,我们可以在定义function的参数时完成解压操作。举例,如果想输入序列[(2,5), (3,2), (10,3)]来得到一个每个元组元素的和的序列[7, 5, 13], 若使用map方法,fun函数将会复杂,而使用startmap则只需要传递一个add函数作为startmap参数,元组解压后的两个值将传入add函数作为参数。

from operator import add
print(list(map(lambda x: add(x[0], x[1]), [(2, 5), (3, 2), (10, 3)])))
print(list(itertools.starmap(add, [(2, 5), (3, 2), (10, 3)])))
## output: [7, 5, 13]

enumerate(iterable, start=0)

enumerate函数也是常见的生成器函数,它的主要用法是提供for-in循环中的索引。若设置start参数,索引将从start值开始逐1增加。

for i, c in enumerate(word, 2):print(i, c)

itertools.accumulate(iterable[, func])

accumulate函数将通过func函数完成逐步累加操作,默认func为operator.add。下面用例子进行说明。

sample = [1, 2, 3, 4, 5]
print(list(itertools.accumulate(sample)))
## output: [1, 3, 6, 10, 15]
print(list(itertools.accumulate(sample, mul)))
## output: [1, 2, 6, 24, 120]
print(list(itertools.accumulate(sample, mul)))
## output: [1, 2, 6, 24, 120]
print(list(itertools.accumulate(sample, min)))
## output: [1, 1, 1, 1, 1]
print(list(itertools.accumulate(sample, max)))
## output: [1, 2, 3, 4, 5]
print(list(itertools.starmap(lambda x, y: y/x, enumerate(itertools.accumulate(sample), 1))))
## output: [1.0, 1.5, 2.0, 2.5, 3.0]

合并生成器

合并生成器接收多个可迭代对象参数,将他们组合后返回新的生成器对象。

itertools.chain(*iterables)

chain生成器函数接收多个可迭代对象参数,将他们按顺序组合成新的生成器对象返回。

print(list(itertools.chain(range(3), range(3, 7))))
## output: [0, 1, 2, 3, 4, 5, 6]

itertools.chain.from_iterable(iterable)

chain.from_iterable函数接收一个元素为可迭对象的可迭代对象,将该所有可迭代的元素拆开,重新按顺序组合成一个新的生成器,新的生成器产出的元素为iterable参数某个元素的解压,chain.from_iterable功能更像是逐层解压迭代对象。

a, b = [1,2], [3,4]
iterable= [[a,b],[a,b]]
print(iterable)
new_iterable = list(itertools.chain.from_iterable(iterable))
print(new_iterable)
print(list(itertools.chain.from_iterable(new_iterable)))
## output:
## [[[1, 2], [3, 4]], [[1, 2], [3, 4]]]
## [[1, 2], [3, 4], [1, 2], [3, 4]]
## [1, 2, 3, 4, 1, 2, 3, 4]

zip(*iterables)

zip函数接收多个iterable参数,并提取每个iterable元素组成元组,返回这些元组组成的生成器对象。

iterable1 = 'abcd'
iterable2 = [1, 2, 3]
iterable3 = [10, 20, 30, 40]
print(list(zip(iterable1, iterable2, iterable3)))
## output:
## [('a', 1, 10), ('b', 2, 20), ('c', 3, 30)]

如果多个iterable元素个数不一致,zip会在最短的iterable耗尽后停止。
我们可以通过zip函数生成一个字典对象

keys = 'abc'
values = [1, 2, 3]
print(dict(zip(keys, values)))
## output: {'a': 1, 'b': 2, 'c': 3}

itertools.zip_longest(*iterables, fillvalue=None)

zip_longes函数作用和zip类似,在zip中如果某个iterable对象耗尽,生成器将就此停止,而zip_longest函数将为耗尽的iterable补充fillvalue值。

iterable1 = 'abcd'
iterable2 = [1, 2, 3]
iterable3 = [10, 20, 30, 40]
print(list(itertools.zip_longest(iterable1, iterable2, iterable3, fillvalue=0)))
## output: [('a', 1, 10), ('b', 2, 20), ('c', 3, 30), ('d', 0, 40)]

itertools.product(*iterables, repeat=1)

product函数计算所有iterable的笛卡尔积,它像是生成器表达式中处理嵌套循环的步骤,product(a, b)可以等同于((x, y) for x in a for y in b)。
repeat相当于扩展了iterables, product(a, b, repeat=2)相当于product(a, b, a, b)

a = (0, 1)
b = (2, 3)
print(list(itertools.product(a, b)))
print(list(itertools.product(a, repeat=2)))## output:
## [(0, 2), (0, 3), (1, 2), (1, 3)]
## [(0, 0), (0, 1), (1, 0), (1, 1)]

扩展生成器

扩展生成器将传进的单一对象进行扩展,生成更多元素组成的生成器对象。

itertools.repeat(object[, times])

repeat函数可以接收一个对象(可以不是可迭代对象), 根据非必选参数times,生成元素个数为times的生成器,如果不提供times参数,将生成无限生成器。

print(list(itertools.repeat(1, 3)))
print(list(itertools.repeat((1, 2), 3)))
print(list(zip(range(1, 4), itertools.repeat('a'))))
print([1, 2] * 3)"""output:
[1, 1, 1]
[(1, 2), (1, 2), (1, 2)]
[(1, 'a'), (2, 'a'), (3, 'a')]
[1, 2, 1, 2, 1, 2]
"""

注意repeat()和列表乘法的区别,通过上文提到的itertools.chain.from_iterable函数结合repeat函数可以实现列表乘法。

lst = [1, 2, 3]
g = itertools.repeat(lst, 3)
print(list(itertools.chain.from_iterable(g)))
print(lst * 3)
"""output
[1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
"""

itertools.cycle(iterable)

cycle函数将传进的iterable可迭代对象首尾相连形成循环,生成无限生成器。

# cycle('ABCD') --> A B C D A B C D A B C D ...

itertools.count(start=0, step=1)

计数器函数,start和step参数可以为小数,直接看例子。

g = itertools.count(1.2, 2.5)
print(next(g))
print(next(g))
print(next(g))
"""output:
1.2
3.7
6.2
"""

上文提到的enumerate生成器函数可以通过map和count来实现。

for i, v in map(lambda x, y: (x, y), itertools.count(), range(3, 10)):print(i, v)

我们可以通过调整count函数让索引i的值更加灵活。
Python中的range(start, stop[, step])函数可以生成一个序列,但是要求输入参数必须为整数,可以通过count函数实现一个可以接收小数的新range。

def range_new(start, stop, step):for i in itertools.count(start, step):if i >= stop:breakyield iprint(list(range_new(1, 5.5, 1.5)))
## output: [1, 2.5, 4.0]

排列组合生成器

以下三个函数可以实现迭代对象的排列组合
itertools.combinations(iterable, r)
非重复组合

print(list(itertools.combinations('ABC', 1)))
print(list(itertools.combinations('ABC', 2)))
print(list(itertools.combinations('ABC', 3)))
"""output:
[('A',), ('B',), ('C',)]
[('A', 'B'), ('A', 'C'), ('B', 'C')]
[('A', 'B', 'C')]
"""

itertools.combinations_with_replacement(iterable, r)
重复组合

print(list(itertools.combinations_with_replacement('ABC', 1)))
print(list(itertools.combinations_with_replacement('ABC', 2)))
print(list(itertools.combinations_with_replacement('ABC', 3)))
"""output:
[('A',), ('B',), ('C',)]
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]
[('A', 'A', 'A'), ('A', 'A', 'B'), ('A', 'A', 'C'), ('A', 'B', 'B'), ('A', 'B', 'C'), ('A', 'C', 'C'), ('B', 'B', 'B'), ('B', 'B', 'C'), ('B', 'C', 'C'), ('C', 'C', 'C')]
"""

itertools.permutations(iterable, r=None)
全排列

print(list(itertools.permutations('ABC', 1)))
print(list(itertools.permutations('ABC', 2)))
print(list(itertools.permutations('ABC', 3)))
"""output:
[('A',), ('B',), ('C',)]
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
"""

对比itertools.product(*iterables, repeat=1)函数

print(list(itertools.product('ABC', repeat=1)))
print(list(itertools.product('ABC', repeat=2)))
"""output:
[('A',), ('B',), ('C',)]
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]
"""

整理生成器

此类生成器将传入的可迭代对象经过整理后,以生成器的形式全部返回。

itertools.groupby(iterable, key=None)

groupby生成器可以根据key,将iterable分组,返回的生成器的元素为(key, iterable)的元组形式。扫描整个序列并且查找连续相同值(或者根据指定 key 函数返回值相同)的元素序列。 在每次迭代的时候,它会返回一个值和一个迭代器对象, 这个迭代器对象可以生成元素值全部等于上面那个值的组中所有对象。

g = itertools.groupby('LLLLAAGGG')
for char, group in g:print(char, '->', list(group))"""output:
L -> ['L', 'L', 'L', 'L']
A -> ['A', 'A']
G -> ['G', 'G', 'G']
"""rows = [{'address': '5412 N CLARK', 'date': '07/01/2012'},{'address': '5148 N CLARK', 'date': '07/04/2012'},{'address': '5800 E 58TH', 'date': '07/02/2012'},{'address': '2122 N CLARK', 'date': '07/03/2012'},{'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},{'address': '1060 W ADDISON', 'date': '07/02/2012'},{'address': '4801 N BROADWAY', 'date': '07/01/2012'},{'address': '1039 W GRANVILLE', 'date': '07/04/2012'},
]rows.sort(key=itemgetter('date'))
g = itertools.groupby(rows, itemgetter('date'))
for char, group in g:print(char, '->', list(group))
"""output:
07/01/2012 -> [{'address': '5412 N CLARK', 'date': '07/01/2012'}, {'address': '4801 N BROADWAY', 'date': '07/01/2012'}]
07/02/2012 -> [{'address': '5800 E 58TH', 'date': '07/02/2012'}, {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'}, {'address': '1060 W ADDISON', 'date': '07/02/2012'}]
07/03/2012 -> [{'address': '2122 N CLARK', 'date': '07/03/2012'}]
07/04/2012 -> [{'address': '5148 N CLARK', 'date': '07/04/2012'}, {'address': '1039 W GRANVILLE', 'date': '07/04/2012'}]
"""

groupby() 仅仅检查连续的元素,因此在调用之前需要根据指定的字段将数据排序。

reversed(seq)

reversed函数接收一个序列(实现sequence相关协议,已知长度)

print(list(reversed(range(5))))
## output: [4, 3, 2, 1, 0]

itertools.tee(iterable, n=2)

tee函数返回单个iterable对象的n个独立迭代器

g1, g2 = itertools.tee('ABC')
print(next(g1), next(g2))
print(next(g1), next(g2))
print(list(zip(*itertools.tee('ABC'))))
"""output
A A
B B
[('A', 'A'), ('B', 'B'), ('C', 'C')]
"""

缩减生成器

接收一个迭代对象,处理只返回一个单一值。

functools.reduce(function, iterable,initializer=None)

function参数是一个接收两个参数的函数function(x, y),reduce函数将上一次function得到的返回值作为参数x,将iterable的下一次迭代值作为参数y传进function计算,初始时x的值为initializer值(若initializer为None,初始值则为iterable的第一个元素值)。循环直到iterable耗尽返回最终值。
reduce的基本实现大概为一下代码:

def reduce(function, iterable, initializer=None):it = iter(iterable)if initializer is None:value = next(it)else:value = initializerfor element in it:value = function(value, element)return value
print(functools.reduce(add, [1, 2, 3, 4, 5]))
## output: 15

常用的min和max函数都可以用reduce实现

def min_reduce(iterable):return functools.reduce(lambda x, y: x if x < y else y, iterable)def max_reduce(iterable):return functools.reduce(lambda x, y: x if x > y else y, iterable)print(min_reduce([4, 6, 6, 78]))
print(max_reduce([4, 6, 6, 78]))
"""output
4
78
"""

除此之外any和all函数原理也是类似,不再阐述。

总结

本篇按照分类介绍了python库中的一些常用的生成器,可以通过不同场景选择不同的生成器工具,将它们组合灵活运用。

相关链接

Python3中的迭代器和生成器

Python3标准库built-in、itertools、functools中的生成器相关推荐

  1. Python书籍推荐:《Python3标准库》

    最近双十一气氛弥漫在整个互联网,不买点东西总觉得缺了什么.在逛某东的时候无意中发现了这本刚出版没多久的书,一时心血来潮立即加入购物车,这不对啊,价格这么贵,而且优惠套路太多了.去当当一看,五折,99. ...

  2. 7.Python3标准库--文件系统

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 ''' Python ...

  3. 第31章 Python3 标准库概览教程

    操作系统接口 os模块提供了不少与操作系统相关联的函数. >>> import os>>> os.getcwd() # return 当前的工作目录'C:\\Pyt ...

  4. python3入门到精通 pdf_解析《Python3标准库》PDF中英文代码+《算法之美指导工作与生活的算法》PDF中英文+《Scratch编程从入门到精通PDF》趣学...

    我想Python之所以流行,原因在于:1. 语言本身优美,表达力强.适合做快速原型开发.且学习曲线平坦,上手快. 2. Python标准库正是应对了这第二点.丰富的库实现得以让python程序员迅速完 ...

  5. 3.Python3标准库--数据结构

    (一)enum:枚举类型 import enum''' enum模块定义了一个提供迭代和比较功能的枚举类型.可以用这个为值创建明确定义的符号,而不是使用字面量整数或字符串 ''' 1.创建枚举 imp ...

  6. python标准库中文版-Python3标准库 PDF 中文完整版

    前言 [0第0]1章 文本 1 1.1 string:文本常量和模板 1 1.1.1 函数 1 1.1.2 模板 2 1.1.3 高级模板 3 1.1.4 Formatter 5 1.1.5 常量 5 ...

  7. python常用标准库有哪些-Python开发中常用的标准库

    大多数基于 Python 开发的应用程序都会用到本地标准库和三方库,这样不仅能让我们把时间去关注真正的业务开发,也能学习到更多价值含量高的程序设计和开发思想.程序开发中有一句著名的话叫做: Don't ...

  8. Python3 标准库及相关内容

    一 .标准库相关 1.操作系统相关接口         操作系统模块,及 os 模块,在引用该模块时,建议使用 " import os" 风格而非 " from os i ...

  9. [雪峰磁针石博客]python3标准库-中文版2:内置函数

    2019独角兽企业重金招聘Python工程师标准>>> 内置功能 abs() dict() help() min() setattr() all() dir() hex() next ...

最新文章

  1. php事件和行为,Yii框架组件和事件行为管理详解
  2. 阿里 Midway 正式发布 Serverless v1.0,研发提效 50%
  3. 【每周NLP论文推荐】 开发聊天机器人必读的重要论文
  4. HDU4349--Xiao Ming's Hope(数论)
  5. 关闭mysql服务的方法有哪些_MySQL--启动和关闭MySQL服务
  6. LVS+piranha(多实例配置) 转载
  7. liteide无法自动补全代码问题解决【go: cannot find GOROOT directory: c:\go】
  8. 小郡肝火锅点餐系统——项目文档
  9. 078、Docker 最常用的监控方案(2019-04-25 周四)
  10. xcode6以后, 使用.pch
  11. mysql界面导出数据库有乱码_导出的MYSQL数据库是乱码还可以变回中文吗
  12. php 单位食堂订餐,职工食堂微信订餐系统 单位饭卡消费系统
  13. m个苹果放入n个盘子
  14. 转载-杭电老师的思考
  15. python另存为对话框_python – 另存为文件对话框 – 如何不允许覆盖
  16. 王雪松等:驾驶行为与驾驶风险国际研究进展
  17. 半导体器件物理【8】平衡半导体 —— 平衡状态、统计力学
  18. Python的数据分析可视化十种技能总结
  19. CentOS8永久修改主机名
  20. Verilog描述有限状态机(一段式、二段式、三段式)

热门文章

  1. Vue3核心概念、新特性及与Vue2的区别
  2. javaScript几种设计模式之一——单体模式
  3. Express-静态资源-路由-ajax-session
  4. 力扣225-用队列实现栈(C++,附思路及优化思路,代码)
  5. 蓝桥杯基础练习之杨辉三角
  6. nmealib linux编译,nmealib的使用可以缩短GPS的开发周期
  7. boot spring 获取请求端口浩_Spring精华问答 | 如何集成Spring Boot?
  8. java 开关按钮_Java Swing JToggleButton开关按钮的实现
  9. 计算机更新80072f76,windows update 80072f76错误
  10. Android View的绘制机制流程深入详解(一)