广告
返回顶部
首页 > 资讯 > 后端开发 > Python >浅析Python自带性能强悍的标准库itertools
  • 256
分享到

浅析Python自带性能强悍的标准库itertools

2024-04-02 19:04:59 256人浏览 薄情痞子

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

摘要

目录前言无限迭代有限迭代排列组合迭代前言   可迭代对象就像密闭容器里的水,有货倒不出 itertools是python内置的标准模块,提供了很多简洁又高效的专用功能,使用得当能够极

前言

 

可迭代对象就像密闭容器里的水,有货倒不出

itertools是python内置的标准模块,提供了很多简洁又高效的专用功能,使用得当能够极大的简化代码行数,同时所有方法都是实现了生成器函数,这就意味着极大的节省内存。

itertools提供的功能主要分为三大块,以最新版本的3.10为例:

  • 对可迭代对象无限迭代,无限输出
  • 对可迭代对象有限迭代
  • 对可迭代对象排列组合

方法如下:

导入包


>>> from iteratortools import *

无限迭代

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

数值生成器,可以指定起始位置和步长,并且步长可以为浮点数。无限输出,一直累加,在例子中需要边睡眠1s边输出。


>>> import time
>>> iterator = count(4, 0.5)
>>> for i in iterator:
...     print(i)
...     time.sleep(1)
...
4
4.5
5.0
5.5
6.0
6.5
7.0
7.5

iteratortools.cycle(iteratorable)

无限循环取出可迭代对象里的元素


>>> a = cycle("ABCD")
>>> import time
>>> for i in a:
...     print(i)
...     time.sleep(1)
...
A
B
C
D
A
B
C
D

iteratortools.repeat(object[, times])

不断重复输出整个object,如果指定了重复次数,则输出指定次数,否则将无限重复。


>>> iterator = repeat('hello world', 10)
>>>
>>> for i in iterator:
...     print(i)
...
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world

有了这个神器,对输出10次hello world这种问题又有一种新解法

有限迭代

iteratortools.accumulate(iteratorable[, func, *, initial=None])

返回对列表中元素逐项的操作,操作有:

  1. 累加,返回累加到每一项的列表
  2. 累乘,返回累乘到每一项的列表
  3. 最小值,返回到当前项的最小值
  4. 最大值,返回到当前项的最大值

>>> [2, 4, 8, 1, 3, 5]
[2, 4, 8, 1, 3, 5]
>>> arr = [2, 4, 8, 1, 3, 5]
>>>
>>> add = accumulate(arr)
>>>
>>> list(add)
[2, 6, 14, 15, 18, 23]
>>>
>>> max = accumulate(arr, max)
>>> list(max)
[2, 4, 8, 8, 8, 8]
>>>
>>> import operator
>>> mul = accumulate(arr, operator.mul)
>>> list(mul)
[2, 8, 64, 64, 192, 960]
>>>
>>> min = accumulate(arr, min)
>>> list(min)
[2, 2, 2, 1, 1, 1]

iteratortools.chain(*iteratorables)

将多个可迭代对象构建成一个新的可迭代对象,统一返回。类似于将多个对象链成一条串


>>> iterator = chain([1,2,3],['a','b','c'],(5,6,7))
>>> list(iterator)
[1, 2, 3, 'a', 'b', 'c', 5, 6, 7]

优点:可以将多个可迭代对象整合成一个,避免逐个取值

chain.from_iteratorable(iteratorable)

将一个迭代对象中将所有元素类似于chain一样,统一返回。


>>> chain.from_iteratorable(['abc','def'])
<iteratortools.chain object at 0x1083ae460>
>>> iterator = chain.from_iteratorable(['abc','def'])
>>> list(iterator)
['a', 'b', 'c', 'd', 'e', 'f']

iteratortools.compress(data, selectors)

按照真值表筛选元素


>>> arr = [1,2,3,4]
>>> selectors = [1,0,1,0]
>>>
>>> iterator = compress(arr, selectors)
>>>
>>> list(iterator)
[1, 3]

iteratortools.dropwhile(predicate, iteratorable)

按照条件筛选,丢弃掉第一次不符合条件时之前的所有元素


>>> arr = [1,2,3,2,1,2,1]
>>> iterator = dropwhile(lambda x: x<3, arr)
>>> list(iterator)
[3, 2, 1, 2, 1]

iteratortools.takewhile(predicate, iteratorable)

根据predicate条件筛选可迭代对象中的元素,只要元素为真就返回,第一次遇到不符合的条件就退出。

按照条件筛选,丢弃第一次遇到不符合条件之后的元素。行为类似于上一个dropwhile,区别在于丢弃的选择不同。

iteratortools.filterfalse(predicate, iteratorable)

保留不符合条件的元素,返回迭代器


>>> arr = [1,2,3,4,5]
>>> iterator = filterfalse(lambda x:x<3, arr)
>>> list(iterator)
[3, 4, 5]

iteratortools.groupby(iteratorable, key=None)

按照指定的条件分类。输出条件和符合条件的元素


>>> iterator = groupby(arr, lambda x: x>3)
>>> for condition ,numbers in iterator:
...     print(condition, list(numbers))
...
False [1, 2, 3]
True [4, 5]

iteratortools.islice(iteratorable, start, stop[, step])

对迭代器进行切片,老版本中不能指定start和stop以及步长,新版本可以。


>>> iterator = count()
>>> slice_iterator = islice(iterator, 10, 20, 2)
>>> list(slice_iterator)
[10, 12, 14, 16, 18]

iteratortools.starmap(function, iteratorable)

将function作用于可迭代对象上,类似于map函数

iteratortools.tee(iteratorable, n=2)

从一个可迭代对象中返回 n 个独立的迭代器


>>> iterator = tee(arr)
>>> for i in iterator:
...     print(type(i), list(i))
...
<class 'iteratortools._tee'> [1, 2, 3, 4, 5]
<class 'iteratortools._tee'> [1, 2, 3, 4, 5]

iteratortools.zip_longest(*iteratorables, fillvalue=None)

创建一个迭代器,从每个可迭代对象中收集元素。如果可迭代对象的长度未对齐,将根据 fillvalue 填充缺失值。

迭代持续到耗光最长的可迭代对象。大致相当于:


>>> iterator = zip_longest("ABCD", "xy", fillvalue="-")
>>> list(iterator)
[('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')]

排列组合迭代

iteratortools.product(*iteratorables, repeat=1)

生成多个可迭代对象的笛卡尔积

大致相当于生成器表达式中的嵌套循环。例如, product(A, B) 和 ((x,y) for x in A for y in B) 返回结果一样。


>>> iterator = product("123", "abc")
>>> list(iterator)
[('1', 'a'), ('1', 'b'), ('1', 'c'), ('2', 'a'), ('2', 'b'), ('2', 'c'), ('3', 'a'), ('3', 'b'), ('3', 'c')]

将可选参数 repeat 设定为要重复的次数。例如,product(A, repeat=4) 和 product(A, A, A, A) 是一样的

iteratortools.permutations(iteratorable, r=None)

由 iteratorable 元素生成长度为 r 的排列。元素的排列,类似于给一个[1,2,3],选取其中两个元素,一共有多少种组合方法?不要求元素排列之后的位置。


>>> iter = permutations([1,2,3], r=3)
>>> list(iterator)
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

这个方法能够完美解决算法中的全排列问题,简直是量身定做。如果早知道这么简单,当年考算法也不会。。,哎

可参见LeetCode46题: 力扣

iteratortools.combinations(iteratorable, r)

返回由输入 iteratorable 中元素组成长度为 r 的子序列。元素不可重复使用。子序列是要求元素在排列之后和之前的相对位置不变的。1,2,3中3在1的后面,子序列中3也一定在1的后面。


>>> iterator = combinations([1,2,3,4], r = 3)
>>> list(iterator)
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
>>> iterator = combinations([1], r = 3)
>>> list(iterator)
[]

这个方法可以曲线解决组合总数问题

力扣

iteratortools.combinations_with_replacement(iteratorable, r)

返回由输入 iteratorable 中元素组成的长度为 r 的子序列,允许每个元素可重复出现


>>> iter = combinations_with_replacement([1,2,3,4], r=2)
>>> list(iter)
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)]

>>> iterator = combinations_with_replacement([1], r=3)
>>> list(iterator)
[(1, 1, 1)]

到此这篇关于浅析Python自带性能强悍的标准库itertools的文章就介绍到这了,更多相关Python 标准库itertools内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 浅析Python自带性能强悍的标准库itertools

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

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

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

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

下载Word文档
猜你喜欢
  • 浅析Python自带性能强悍的标准库itertools
    目录前言无限迭代有限迭代排列组合迭代前言   可迭代对象就像密闭容器里的水,有货倒不出 itertools是python内置的标准模块,提供了很多简洁又高效的专用功能,使用得当能够极...
    99+
    2022-11-12
  • Python标准库的强大功能的示例分析
    Python标准库的强大功能的示例分析,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。Python标准库是十分庞大的,其中也有一些质量比较高的库,例如,wXPython、Py...
    99+
    2023-06-17
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作