广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python中itertools模块的使用教程详解
  • 289
分享到

Python中itertools模块的使用教程详解

2024-04-02 19:04:59 289人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录itertools模块的介绍无限迭代器(Infinite Iterators)组合迭代器(Combinatoric Iterators)有限迭代器(Iterators Termi

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

到此这篇关于Python中itertools模块的使用教程详解的文章就介绍到这了,更多相关Python itertools模块内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Python中itertools模块的使用教程详解

本文链接: https://www.lsjlt.com/news/117793.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作