当前位置:Gxlcms > Python > Python迭代器工具包【推荐】

Python迭代器工具包【推荐】

时间:2021-07-01 10:21:17 帮助过:63人阅读

0x01 介绍了迭代器的概念,即定义了 __iter__() __next__() 方法的对象,或者通过 yield 简化定义的“可迭代对象”,而在一些函数式编程语言(见 0x02 Python 中的函数式编程)中,类似的迭代器常被用于产生特定格式的列表(或序列),这时的迭代器更像是一种数据结构而非函数(当然在一些函数式编程语言中,这两者并无本质差异)。Python 借鉴了 APL, Haskell, and SML 中的某些迭代器的构造方法,并在 itertools 中实现(该模块是通过 C 实现,源代码:/Modules/itertoolsmodule.c)。

  itertools 模块提供了如下三类迭代器构建工具:

  无限迭代

  整合两序列迭代

  组合生成器

  1. 无限迭代

  所谓无限(infinite)是指如果你通过 for...in... 的语法对其进行迭代,将陷入无限循环,包括:  

  1. count(start, [step])
  2.   cycle(p)
  3.   repeat(elem [,n])

  从名字大概可以猜出它们的用法,既然说是无限迭代,我们自然不会想要将其所有元素依次迭代取出,而通常是结合 map/zip 等方法,将其作为一个取之不尽的数据仓库,与有限长度的可迭代对象进行组合操作:  

  1. from itertools import cycle, count, repeat
  2. print(count.__doc__)
  3.   count(start=0, step=1) --> count object
  4.   Return a count object whose .__next__() method returns consecutive values.
  5.   Equivalent to:
  6.   def count(firstval=0, step=1):
  7.   x = firstval
  8.   while 1:
  9.   yield x
  10.   x += step
  11.   counter = count()
  12.   print(next(counter))
  13. print(next(counter))
  14.   print(list(map(lambda x, y: x+y, range(10), counter)))
  15.   odd_counter = map(lambda x: 'Odd#{}'.format(x), count(1, 2))
  16. print(next(odd_counter))
  17.   print(next(odd_counter))
  18.   0
  19.   1
  20.   [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
  21.   Odd#1
  22.   Odd#3
  23.   print(cycle.__doc__)
  24.   cycle(iterable) --> cycle object
  25.   Return elements from the iterable until it is exhausted.
  26.   Then repeat the sequence indefinitely.
  27.   cyc = cycle(range(5))
  28.   print(list(zip(range(6), cyc)))
  29.   print(next(cyc))
  30.   print(next(cyc))
  31.   [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 0)]
  32.   1
  33.   2
  34.   print(repeat.__doc__)
  35.   repeat(object [,times]) -> create an iterator which returns the object
  36.   for the specified number of times. If not specified, returns the object
  37.   endlessly.
  38.   print(list(repeat('Py', 3)))
  39.   rep = repeat('p')
  40.   print(list(zip(rep, 'y'*3)))
  41.   ['Py', 'Py', 'Py']
  42.   [('p', 'y'), ('p', 'y'), ('p', 'y')]

  2. 整合两序列迭代

  所谓整合两序列,是指以两个有限序列为输入,将其整合操作之后返回为一个迭代器,最为常见的 zip 函数就属于这一类别,只不过 zip 是内置函数。这一类别完整的方法包括: 

  1.  accumulate()
  2.   chain()/chain.from_iterable()
  3.   compress()
  4.   dropwhile()/filterfalse()/takewhile()
  5.   groupby()
  6.   islice()
  7.   starmap()
  8.   tee()
  9.   zip_longest()

  这里就不对所有的方法一一举例说明了,如果想要知道某个方法的用法,基本通过 print(method.__doc__) 就可以了解,毕竟 itertools 模块只是提供了一种快捷方式,并没有隐含什么深奥的算法。这里只对下面几个我觉得比较有趣的方法进行举例说明。  

  1. from itertools import cycle, compress, islice, takewhile, count
  2.   # 这三个方法(如果使用恰当)可以限定无限迭代
  3.   # print(compress.__doc__)
  4.   print(list(compress(cycle('PY'), [1, 0, 1, 0])))
  5.   # 像操作列表 l[start:stop:step] 一样操作其它序列
  6.   # print(islice.__doc__)
  7.   print(list(islice(cycle('PY'), 0, 2)))
  8.   # 限制版的 filter
  9.   # print(takewhile.__doc__)
  10.   print(list(takewhile(lambda x: x < 5, count())))
  11.   ['P', 'P']
  12.   ['P', 'Y']
  13.   [0, 1, 2, 3, 4]
  14.   from itertools import groupby
  15.   from operator import itemgetter
  16.   print(groupby.__doc__)
  17.   for k, g in groupby('AABBC'):
  18.   print(k, list(g))
  19.   db = [dict(name='python', script=True),
  20.   dict(name='c', script=False),
  21.   dict(name='c++', script=False),
  22.   dict(name='ruby', script=True)]
  23.   keyfunc = itemgetter('script')
  24.   db2 = sorted(db, key=keyfunc) # sorted by `script'
  25.   for isScript, langs in groupby(db2, keyfunc):
  26.   print(', '.join(map(itemgetter('name'), langs)))
  27.   groupby(iterable[, keyfunc]) -> create an iterator which returns
  28.   (key, sub-iterator) grouped by each value of key(value).
  29.   A ['A', 'A']
  30.   B ['B', 'B']
  31.   C ['C']
  32.   c, c++
  33.   python, ruby
  34.   from itertools import zip_longest
  35.   # 内置函数 zip 以较短序列为基准进行合并,
  36.   # zip_longest 则以最长序列为基准,并提供补足参数 fillvalue
  37.   # Python 2.7 中名为 izip_longest
  38.   print(list(zip_longest('ABCD', '123', fillvalue=0)))
  39.   [('A', '1'), ('B', '2'), ('C', '3'), ('D', 0)]

  3. 组合生成器

  关于生成器的排列组合: 

  1. product(*iterables, repeat=1):两输入序列的笛卡尔乘积
  2.   permutations(iterable, r=None):对输入序列的完全排列组合
  3.   combinations(iterable, r):有序版的排列组合
  4.   combinations_with_replacement(iterable, r):有序版的笛卡尔乘积
  5.   from itertools import product, permutations, combinations, combinations_with_replacement
  6.   print(list(product(range(2), range(2))))
  7.   print(list(product('AB', repeat=2)))
  8.   [(0, 0), (0, 1), (1, 0), (1, 1)]
  9.   [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]
  10.   print(list(combinations_with_replacement('AB', 2)))
  11.   [('A', 'A'), ('A', 'B'), ('B', 'B')]
  12.   # 赛马问题:4匹马前2名的排列组合(A^4_2)
  13.   print(list(permutations('ABCDE', 2)))
  14.   [('A', 'B'), ('A', 'C'), ('A', 'D'),
  15. ('A', 'E'), ('B', 'A'), ('B', 'C'),
  16. ('B', 'D'), ('B', 'E'), ('C', 'A'),
  17. ('C', 'B'), ('C', 'D'), ('C', 'E'),
  18. ('D', 'A'), ('D', 'B'), ('D', 'C'),
  19. ('D', 'E'), ('E', 'A'), ('E', 'B'), ('E', 'C'), ('E', 'D')]
  20.   # 彩球问题:4种颜色的球任意抽出2个的颜色组合(C^4_2)
  21.   print(list(combinations('ABCD', 2)))
  22.   [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]

人气教程排行