Python中itertools模块的使用教程详解
作者:百晓生 发布时间:2023-08-24 03:07:25
itertools模块的介绍
在Python中,迭代器(Iterator)是常用来做惰性序列的对象,只有当迭代到某个值的时候,才会进行计算得出这个值。因此,迭代器可以用来存储无限大的序列,这样我们就不用把他一次性放在内存中,而只在需要的时候进行计算。所以,对于读取大文件或者无线集合,最好是使用迭代器。实际上,Python2的大多数函数都是返回列表等序列,而Python3都已经改进为返回迭代器。
Python的内置模块itertools就是用来操作迭代器的一个模块,包含的函数都是能够创建迭代器来用于for循环或者next()。其中函数主要可以分为三类,分别是无限迭代器,有限迭代器,组合迭代器。
无限迭代器(Infinite Iterators)
这些函数可以生成无限的迭代器,我们主要学习以下三个函数的用法。
count([start=0, step=1]) 接收两个可选整形参数,第一个指定了迭代开始的值,第二个指定了迭代的步长。此外,start参数默认为0,step参数默认为1,可以根据需要来把这两个指定为其它值,或者使用默认参数。
import itertools
for i in itertools.count(10,2):
print(i)
if i>20:
break
[Running] python -u "e:\pythonee\code\test.py"
10
12
14
16
18
20
22
cycle(iterable) 是用一个可迭代对象中的元素来创建一个迭代器,并且复制自己的值,一直无限的重复下去。
import itertools
for i in itertools.cycle("abcd"):
print(i) # 具有无限的输出,可以按ctrl+c来停止。
[Running] python -u "e:\pythonee\code\test.py"
a
b
c
d
a
b
c
d
a
b
repeat(elem [,n])是将一个元素重复n遍或者无穷多遍,并返回一个迭代器。
import itertools
for i in itertools.repeat("abcd",5):
print(i)
[Running] python -u "e:\pythonee\code\test.py"
abcd
abcd
abcd
abcd
abcd
组合迭代器(Combinatoric Iterators)
组合操作包括排列,笛卡儿积,或者一些离散元素的选择,组合迭代器就是产生这样序列的迭代器。我们来看看这几个函数的用法。
product(*iterables, repeat=1) 得到的是可迭代对象的笛卡儿积,*iterables参数表示需要多个可迭代对象。这些可迭代对象之间的笛卡儿积,也可以使用for循环来实现,例如 product(A, B) 与 ((x,y) for x in A for y in B)就实现一样的功能。
import itertools
for i in itertools.product([1,2,3],[4,5,6]):
print(i)
[Running] python -u "e:\pythonee\code\test.py"
(1, 4)
(1, 5)
(1, 6)
(2, 4)
(2, 5)
(2, 6)
(3, 4)
(3, 5)
(3, 6)
而 repeat 参数则表示这些可迭代序列重复的次数。例如 product(A, repeat=4) 与 product(A, A, A, A)实现的功能一样。
import itertools
for i in itertools.product('ab','cd',repeat = 2):
print(i)
[Running] python -u "e:\pythonee\code\test.py"
('a', 'c', 'a', 'c')
('a', 'c', 'a', 'd')
('a', 'c', 'b', 'c')
('a', 'c', 'b', 'd')
('a', 'd', 'a', 'c')
('a', 'd', 'a', 'd')
('a', 'd', 'b', 'c')
('a', 'd', 'b', 'd')
('b', 'c', 'a', 'c')
('b', 'c', 'a', 'd')
('b', 'c', 'b', 'c')
('b', 'c', 'b', 'd')
('b', 'd', 'a', 'c')
('b', 'd', 'a', 'd')
('b', 'd', 'b', 'c')
('b', 'd', 'b', 'd')
permutations(iterable,r=None)返回的是可迭代元素中的一个排列组合,并且是按顺序返回的,且不包含重复的结果。
import itertools
for i in itertools.permutations('abc'):
print(i)
[Running] python -u "e:\pythonee\code\test.py"
('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
当然,第 2 个参数默认为None,它表示的是返回元组(tuple) 的长度,我们来尝试一下传入第二个参数。
import itertools
for i in itertools.permutations('abc',2):
print(i)
[Running] python -u "e:\pythonee\code\test.py"
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'c')
('c', 'a')
('c', 'b')
combinations(iterable,r) 返回的是可迭代对象所有的长度为 r 的子序列,注意这与前一个函数 permutation 不同,permutation 返回的是排列,而 combinations 返回的是组合。
import itertools
for i in itertools.combinations('1234',2):
print(i)
[Running] python -u "e:\pythonee\code\test.py"
('1', '2')
('1', '3')
('1', '4')
('2', '3')
('2', '4')
('3', '4')
combinations_with_replacement(iterable, r) 返回一个可与自身重复的元素组合,用法类似于 combinations 。
import itertools
for i in itertools.combinations_with_replacement('1234',2):
print(i)
[Running] python -u "e:\pythonee\code\test.py"
('1', '1')
('1', '2')
('1', '3')
('1', '4')
('2', '2')
('2', '3')
('2', '4')
('3', '3')
('3', '4')
('4', '4')
有限迭代器(Iterators Terminating on the Shortest Input Sequence)
这里的函数有十来个,主要为大家介绍其中几个常用的函数。
chain(*iterables) 可以把多个可迭代对象组合起来,形成一个更大的迭代器。
import itertools
for i in itertools.chain('good','bye'):
print(i)
[Running] python -u "e:\pythonee\code\test.py"
g
o
o
d
b
y
e
groupby(iterable,key=None) 可以把相邻元素按照 key 函数分组,并返回相应的 key 和 groupby,如果key函数为 None,则只有相同的元素才能放在一组。
import itertools
for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
print(list(group))
[Running] python -u "e:\pythonee\code\test.py"
['A', 'a', 'a']
['B', 'B', 'b']
['c', 'C']
['A', 'A', 'a']
accumulate(iterable [,func]) 可以计算出一个迭代器,这个迭代器是由特定的二元函数的累计结果生成的,如果不指定的话,默认函数为求和函数。
import itertools
for i in itertools.accumulate([0,1,0,1,1,2,3,5]):
print(i)
[Running] python -u "e:\pythonee\code\test.py"
0
1
1
2
3
5
8
13
如果我们指定这个累计函数,则还能有不同的用法,例如,指定一个最大值函数,或者自己定义的函数。
import itertools
for i in itertools.accumulate([2,1,4,3,5],max):
print(i)
[Running] python -u "e:\pythonee\code\test.py"
2
2
4
4
5
来源:https://zhuanlan.zhihu.com/p/51003123


猜你喜欢
- SQLSERVER与MySQL的差异功能差异SQLServer和MySQL都支持大多数SQL语言的基本功能,如SELECT,UPDATE,I
- 本文实例讲述了python开发中range()函数用法。分享给大家供大家参考,具体如下:python中的range()函数的功能很强大,所以
- 一、关于exists查询explain select * from vendor where EXISTS(select * from ar
- 今天用numpy 的linalg.det()求矩阵的逆的过程中出现了一个错误:TypeError: No loop matching the
- 如何阻止别人非法链接你网站的图片,防盗链?getimage.asp<% Option ExplicitDim&nb
- 先简单说一下MP3的ID3 标记,因为主要是操作这个玩意MP3最开始的时候没有我们今天看到的那样,有歌手、年代,专集等等信息只有一些简单的参
- 当你用 ASP 编写服务器端应用程序时,必须依靠 ActiveX
- 1、标准转换格式符号说明%a 本地星期的短名称 如:Sun, Mon, ..., Sat (en_US); So, Mo, ..., Sa
- 前言在Python开发中,有些情况下,我们可能面临在一台机器上同时安装多版本Python的需求。比如:有多个Python项目,每个项目依赖不
- 我最近在参与Python字节码相关的工作,想与大家分享一些这方面的经验。更准确的说,我正在参与2.6到2.7版本的CPython解释器字节码
- 第一步: 1:磁盘寻道能力,以高速硬盘(7200转/秒),理论上每秒寻道7200次.这是没有办法改变的,优化的方法是----用多个硬盘,或者
- HTTP应答头概述 Web服务器的HTTP
- 本文实例为大家分享了python发送邮件的具体代码,供大家参考,具体内容如下#!/usr/bin/env python # -*- codi
- 设计页面时,经常会从一个页面打开一个子窗口以供浏览者查看。通常,这种子窗口中的内容一经浏览者看过,对于浏览者而言就不再需要,而他们常常会忘记
- 前言在学习go语言时,做算法题会很经常遇到go语言的各种int类型,为什么会有int、int8、int16等等的类型呢?为什么不像java一
- 之前用Python 2.7版本的httplib做接口测试时,运行代码都是正常的,最近开始用Python 3.3之后,再去看以前的代码,发现i
- 按照固定的字符,拆分已有的字符串split(sep, n, expand = False):sep:用于分割的字符串n:分割为多少列expa
- 原作者:Jonathan 翻译:charlee原文:http://f6design.com/journal/2006/10/21/the-v
- 简介有些 post 的请求参数是 json 格式的,这个前面发送post 请求里面提到过,需要导入 json模块处理。现在企业公司一般常见的
- 目录1安装loguru|2loguru简单使用|3loguru保留日志文件|4loguru字符串输出|5loguru封装类,可以直接拿去用!