zoukankan      html  css  js  c++  java
  • python自带性能强悍的标准库 itertools

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

    1. 对可迭代对象无限迭代,无限输出
    2. 对可迭代对象有限迭代
    3. 对可迭代对象排列组合

    方法如下:

    导入包

    >>> 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]
    

    groupby时传入的数组是否有序很关键,对于有序的数组,groupby之后会产生两个记录,如[1,2,3,4,5,6]按照大于4区分,得到的就是

    False [1,2,3]
    True [4,5,6]
    

    如果列表是无序的,如[1,3,5,2,4,6],那么得到的就是

    True  1
    True  3  
    False 5
    True  2
    False 4
    True 6
    

    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题:https://leetcode-cn.com/problems/permutations/

    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)
    []
    

    这个方法可以曲线解决组合总数问题
    https://leetcode-cn.com/problems/combination-sum/

    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)]
    
  • 相关阅读:
    简单canvas五子棋
    javascript高级程序第三版学习笔记【执行环境、作用域】
    Error对象
    表单元素input、按钮、文字完美垂直居中对齐方法
    Firebug控制台详解
    JavaScript,JScript,ECMAScript及对应浏览器的版本
    valueOf和toString
    javascript高级程序第三版学习笔记【基本类型和引用类型】
    图的实现(邻接链表C#)
    基本排序算法(C)
  • 原文地址:https://www.cnblogs.com/goldsunshine/p/15678828.html
Copyright © 2011-2022 走看看