Python 内置的 itertools 模块使用了 yield 生成器。

1. chain 拼接迭代器

chain 函数实现元素拼接,原型如下,参数 * 表示可变的参数:

chain(*iterables)

使用方法:

In [15]: from itertools import chain

In [16]: a = chain(['This', 'is'], ["python", "qtconsole"])

In [17]: type(a)
Out[17]: itertools.chain

In [18]: for i in a:
    ...:     print(i)
    ...:     
This
is
python
qtconsole

2. accumulate 累积迭代器

累积迭代器返回可迭代对象的累积迭代器,函数原型:

accumulate(iterable[, func, *, initial=None])

如果 func 不提供,默认求累积和,使用示例如下:

In [19]: from itertools import accumulate

In [20]: a = accumulate([1,2,3,4])

In [21]: for i in a:
    ...:     print(i)
    ...:     
1
3
6
10

In [22]: 

如果 func 提供, func 的参数个数要求为 2,根据 func 的累积行为返回结果。

In [22]: a = accumulate([1,2,3,4], lambda x,y: x*y)

In [23]: for i in a:
    ...:     print(i)
    ...:     
1
2
6
24

In [24]: 

3. compress 漏斗迭代器

compress 函数,功能类似于漏斗功能,所以称它为漏斗迭代器,原型:

compress(data, selectors)

经过 selectors 过滤后,返回一个更小的迭代器。

In [29]: a = compress("helloworld", [1,0,1,0])

In [30]: for i in a:
    ...:     print(i)
    ...:     
h
l

In [31]: 

compress 返回元素个数,等于两个参数中较短序列的长度。

4. drop 迭代器

扫描可迭代对象 iterable ,从不满足条件处往后全部保留,返回一个更小的迭代器。
函数原型如下:

dropwhile(predicate, iterable)

使用示例:

In [31]: from itertools import dropwhile

In [32]: a = dropwhile(lambda x: x> 5, [1,2,6,7,0])

In [33]: for i in a:
    ...:     print(i)
    ...:     
1
2
6
7
0

In [34]: a = dropwhile(lambda x: x> 5, [9,8,2,7,0])

In [35]: for i in a:
    ...:     print(i)
    ...:     
2
7
0

In [36]: 

5. take 迭代器

扫描列表,只要满足条件就从可迭代对象中返回元素,直到不满足条件为止,原型如下:

takewhile(predicate, iterable)

使用示例:

In [36]: from itertools import takewhile

In [37]: a = takewhile(lambda x:x>5, [9,8,2,7,0])

In [38]: for i in a:
    ...:     print(i)
    ...:     
9
8

In [39]: 

6. 加强版 zip

若可迭代对象的长度未对齐,将根据 fillvalue 填充缺失值,返回结果的长度等于更长的序列长度。

In [39]: from itertools import zip_longest

In [40]: list(zip_longest("abcd", "xy", fillvalue="-"))
Out[40]: [('a', 'x'), ('b', 'y'), ('c', '-'), ('d', '-')]

In [41]: 

7. 笛卡尔积

笛卡尔积实现的效果,同下:

((x,y) for x in A for y in B)

使用示例:

In [41]: from itertools import product

In [42]: list(product("abcd", "12"))
Out[42]: 
[('a', '1'),
 ('a', '2'),
 ('b', '1'),
 ('b', '2'),
 ('c', '1'),
 ('c', '2'),
 ('d', '1'),
 ('d', '2')]

In [43]: 

8. 复制元素

repeat 实现复制元素 n 次,原型如下:

repeat(object[, times])

使用示例:

In [43]: from itertools import repeat

In [44]: list(repeat(2,3))
Out[44]: [2, 2, 2]

In [45]: list(repeat([1,2],3))
Out[45]: [[1, 2], [1, 2], [1, 2]]

In [46]: list(repeat({},3))
Out[46]: [{}, {}, {}]

In [47]: 
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐