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
猜你喜欢
- 一、记事本源码#python简易记事本from tkinter import *from tkinter import messagebox
- 如何侦测HTTP表头信息?可用下列办法侦测并显示所有的HTTP HEADERS:<HTML><HEAD><TI
- 前言写过前端Javascript代码的同学肯定不会对console对象感到陌生,在调试的过程中我们经常会用console对象在控制台输出一些
- scapy是python写的一个功能强大的交互式数据包处理程序,可用来发送、嗅探、解析和伪造网络数据包,常常被用到网络攻击和测试中。这里就直
- API照例,我们搬一下官网的 API:C++void cv::filter2D(InputArray src,
- Crawler全名是DomCrawler,是Symfony框架的组件。令人发指的是DomCrawler的没有中文文档,Symfony也没有翻
- 两个例子package main import ( "fmt" "time")func Proces
- 最近一直在用Vs2013调试编译opencv,意外发现一个超级赞的图片查看的插件, 超级方便易用的一个插件,直接以图片形式可视化了openc
- Python continue语句:当执行到 continue 语句时,将不再执行本次循环中 continue 语句接下来的部分,而是继续下
- 最近看到一个内部项目的插件加载机制,非常赞。当然这里说的插件并不是指的golang原生的可以在buildmode中加载指定so文件的那种加载
- 前言首先来看一段代码x_list = [i for i in range(30)]y_list = [i for i in range(10
- 随机数和蒙特卡洛模拟求解单一变量非线性方程求解线性系统方程函数的数学积分常微分方程的数值解等势线绘图和曲线:等势线 import
- 之前有写过一篇浏览器的tab设计,这回说说网站的tab设计。一说到tab很自然地就想到了导航、信息架构。随着网站信息结构的复杂化,选择tab
- 这个自定义损失函数的背景:(一般回归用的损失函数是MSE, 但要看实际遇到的情况而有所改变)我们现在想要做一个回归,来预估某个商品的销量,现
- 服务器响应HTTP的类型ContentType大全,使用方法:<% Response.ContentType =&
- 本文实例讲述了python排序方法。分享给大家供大家参考。具体如下:>>> def my_key1(x):... &nbs
- 代码如下:---1.平均销售等待时间 ---有一张Sales表,其中有销售日期与顾客两列,现在要求使用一条SQL语句实现计算 --每个顾客的
- django处理Ajax跨域访问使用javascript进行ajax访问的时候,出现如下错误出错原因:javascript处于安全考虑,不允
- 一、前言对很多人来说,将PDF转换为可编辑的文本是个刚需,却苦于没有简单的方法。发现 pdf 幻灯片,效果还不错。传统的讲座通常伴随有很多p
- 作者:HelloGitHub-追梦人物 文中所涉及的示例代码,已同步更新到 HelloGitHub-Team 仓库博客提供 RSS