Z.S.K.'s Records

python迭代器模块itertools常用方法

itertools是python中内置的一种高效的生成各种迭代器或者是类的模块,这些函数的返回值为一个迭代器,经常被用在for循环中,当然,也可直接使用next()方法取值,今天就来说说itertools中的常用方法.

itertools按照迭代器的功能可分为三类:

  • 无限迭代器: 生成一个无限序列,比如自然数序列 1, 2, 3, 4, …
  • 有限迭代器: 接收一个或多个序列(sequence)作为参数,进行组合、分组和过滤等;
  • 组合迭代器: 序列的排列、组合,求序列的笛卡儿积等

无限迭代器

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
itertools.count(start=0, step=1)
#创建一个迭代器,生成从n开始的连续整数,如果忽略n,则从0开始计算(注意:此迭代器不支持长整数),如果超出了sys.maxint,计数器将溢出并继续从-sys.maxint-1开始计算
#start: 起始值,默认为0,
#step: 步长,默认为1

import itertools
a = itertools.count()
for x in a:
if x > 5:
break
print(x)
#输出:
1
2
3
4
5
6

b = itertools.count(2,3)
for x in b:
if x > 10:
break
print(x)
#输出
2
5
8

itertools.cycle(iterable)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
itertools.cycle(iterable)
#创建一个迭代器,对iterable中的元素反复执行循环操作,内部会生成iterable中的元素的一个副本,此副本用于返回循环中的重复项
#iterable: 可迭代对象,可以为一个列表、字符串、元组等

import itertools
a = ['a','b','c']
i = 0
for x in itertools.cycle(a):
i = i +1
if i > 5:
break
print(i,x)

#输出
1,'a'
2,'b'
3,'c'
4,'a'
5,'b'

itertools.repeat(object[, times])

1
2
3
4
5
6
7
8
9
10
11
12
13
itertools.repeat(object[, times])
#创建一个迭代器,重复生成object,times(如果已提供)指定重复计数,如果未提供times,将无止尽返回该对象
#object: 需要重复的对象,对象是个整体
#times: 重复次数

import itertools
for x in itertools.repeat([1,2,3],3):
print(x)

#输出
[1,2,3]
[1,2,3]
[1,2,3]

有限迭代器

itertools.chain(iterable1, iterable2, …)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
itertools.chain(iterable1, iterable2, ...)
#将多个迭代器作为参数, 但只返回单个迭代器, 它产生所有参数迭代器的内容, 就好像他们是来自于一个单一的序列
#参数为多个可迭代对象,就好像被链条衔接起来了一样

import itertools
for x in itertools.chain([1,2,3],'abc'):
print(x)

#输出
1
2
3
'a'
'b'
'c'

for x in itertools.chain([1,2,3],['a','b','c']):
print(x)
#输出
1
2
3
'a'
'b'
'c'

itertools.chain.from_iterable(iterable)

1
2
3
4
5
6
7
8
9
10
11
12
itertools.chain.from_iterable(iterable)
#接收一个可迭代对象作为参数,返回一个迭代器

from itertools import chain
a = [['first','second','thrid'],['a','b','c']]
b = [[1,2,3],[4,5,6]]
for x in range(len(a)):
list(chain.from_iterable(zip(a[x],b[x])))

#输出
['first', 1, 'second', 2, 'thrid', 3]
['a', 4, 'b', 5, 'c', 6]

itertools.compress(data, selectors)

1
2
3
4
5
6
7
8
9
10
11
12
13
itertools.compress(data, selectors)
#可用于对数据进行筛选,当 selectors 的某个元素为 true 时,则保留 data 对应位置的元素,否则去除
#data: 待筛选数据
#selectors: 当为真时,保留data对应位的数据,为假或为空时则去除

from itertools import compress
for x in compress(['a','b','c','d'],[1,0,2]):
print(x)

#输出
'a'
'c'
# 2 也为真,'d'对应值为空算假

itertools.dropwhile(predicate, iterable)

1
2
3
4
5
6
7
8
9
10
itertools.dropwhile(predicate, iterable)
#创建一个迭代器,只要函数predicate(item)为True,就丢弃iterable中的项,如果predicate返回False,就会生成iterable中的项和所有后续项,即第一个不满足条件的项及它后面所有的项都返回
#predicate: 函数
#iterable: 可迭代对象

from itertools import dropwhile
list(dropwhile(lambda x: x < 5, [1, 3, 6, 2, 1]))
#输出:
[6,2,1]
#从6开始不符合x < 5 条件,所以6及6后面所有的项都需要返回

itertools.takewhile(predicate, iterable)

1
2
3
4
5
6
7
itertools.takewhile(predicate, iterable)
#创建一个迭代器,如果predicate返回False,立即停止迭代

from itertools import takewhile
list(takewhile(lambda x: x < 5, [1, 3, 6, 2, 1]))
#输出
[1,3]

itertools.ifilter(predicate, iterable)

1
2
3
4
5
6
7
8
9
itertools.ifilter(predicate, iterable)
#创建一个迭代器,仅生成iterable中predicate(item)为True的项,如果predicate为None,将返回iterable中所有计算为True的项
#predicate: 函数
#iterable: 可迭代对象

from itertools import ifilter
list(ifilter(lambda x: x < 5, [1, 3, 6, 2, 1]))
#输出:
[1,3,2,1]

itertools.ifilterfalse(predicate, iterable)

1
2
3
4
5
6
7
8
9
itertools.ifilterfalse(predicate, iterable)
#创建一个迭代器,仅生成iterable中predicate(item)为False的项,如果predicate为None,将返回iterable中所有计算False的项,该函数正好跟ifilter相反
#predicate: 函数
#iterable: 可迭代对象

from itertools import ifilterfalse
list(ifilterfalse(lambda x: x < 5, [1, 3, 6, 2, 1]))
#输出:
[6]

itertools.groupby(iterable[, key])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
itertools.groupby(iterable[, key])
#返回一个产生按照key进行分组后的值集合的迭代器
#iterable:可迭代对象
#key: 一个函数,该函数的返回值做为分组的标准

from itertools import groupby
a = ['aa', 'ab', 'abc', 'bcd', 'abcde']
for i, k in groupby(a, len):
print (i, list(k))

#输出
2,['aa', 'ab']
3,['abc', 'bcd']
5,['abcde']

itertools.islice(iterable, stop)

1
2
3
4
5
6
7
8
9
10
11
12
itertools.islice(iterable,[start], stop,[step])
#iterable 是可迭代对象,start 是开始索引,默认为0,stop 是结束索引,step 是步长,默认为1,start 和 step 可选

from itertools import islice,count
list(islice([10, 6, 2, 8, 1, 3, 9], 5))
#输出
[[10, 6, 2, 8, 1]

list(islice(count(), 3, 10 ,2))
#输出
[3,5,7,9]
#这里的count()为文章第一个函数,用来产生无限序列

itertools.imap(func, iter1, iter2, iter3, …)

1
2
3
4
5
6
7
8
9
imap(func, iter1, iter2, iter3, ...)
#返回一个迭代器, 它是调用了一个其值在输入迭代器上的函数, 返回结果. 它类似于内置函数 map() , 只是前者在任意输入迭代器结束后就停止(而不是插入None值来补全所有的输入)
#注意: 该函数在python3.x中已不存在,可直接使用map

from itertools import imap
list(imap(pow, [2, 3, 10], [4, 2, 3]))
#输出
[16, 9, 1000]
#pow函数 求指数

**itertools.izip(*iterables)**

1
2
3
4
5
6
7
8
9
10
11
12
itertools.izip(*iterables)
#用于将多个可迭代对象对应位置的元素作为一个元组,将所有元组『组成』一个迭代器,并返回
#注意: 该函数在python3.x中已不存在,可直接使用zip

from itertools import izip
for item in izip([1, 2, 3], ['a', 'b', 'c', 'd', 'e']):
print(item)

#输出
(1, 'a')
(2, 'b')
(3, 'c')

**itertools.izip_longest(*iterables, [fillvalue=None])**

1
2
3
4
5
6
7
8
9
10
11
12
13
14
itertools.izip_longest(*iterables,[fillvalue=None])
#izip_longest 跟 izip 类似,但迭代过程会持续到所有可迭代对象的元素都被迭代完
#注意: 该函数在python3.x中已不存在

from itertools import izip_longest
for item in izip_longest([1, 2, 3], ['a', 'b', 'c', 'd', 'e'],fillvalue='-'):
print(item)

#输出
(1, 'a')
(2, 'b')
(3, 'c')
('-','d')
('-','e')

组合迭代器

*itertools.product(iterables[, repeat])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
itertools.product(*iterables[, repeat])
#创建一个迭代器,生成表示item1,item2等中的项目的笛卡尔积的元组,repeat是一个关键字参数,指定重复生成序列的次数。
# 用来产生笛卡尔积

import itertools
a = (1, 2, 3)
b = ('A', 'B', 'C')
c = itertools.product(a,b)
for elem in c:
print(elem)

#输出
(1, 'A')
(1, 'B')
(1, 'C')
(2, 'A')
(2, 'B')
(2, 'C')
(3, 'A')
(3, 'B')
(3, 'C')

list(product((0,1), (0,1), (0,1)))
#输出
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

list(product('ABC', repeat=2))
#输出
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]

itertools.permutations(iterable[, r])

1
2
3
4
5
6
7
itertools.permutations(iterable[, r])
#创建一个迭代器,返回iterable中所有长度为r的项目序列,如果省略了r,那么序列的长度与iterable中的项目数量相同: 返回p中任意取r个元素做排列的元组的迭代器

from itertools import permutations
list(permutations('ABC', 2))
#输出
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]

itertools.combinations(iterable, r)

1
2
3
4
5
6
7
itertools.combinations(iterable, r)
#创建一个迭代器,返回iterable中所有长度为r的子序列,返回的子序列中的项按输入iterable中的顺序排序 (不带重复)

from itertools import combinations
list(combinations('ABC', 2))
#输出
[('A', 'B'), ('A', 'C'), ('B', 'C')]

itertools.combinations_with_replacement(iterable, r)

1
2
3
4
5
6
7
itertools.combinations_with_replacement(iterable, r)
#创建一个迭代器,返回iterable中所有长度为r的子序列,返回的子序列中的项按输入iterable中的顺序排序 (带重复)

from itertools import combinations_with_replacement
list(combinations_with_replacement('ABC', 2))
#输出
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]

参考文章:

转载请注明原作者: 周淑科(https://izsk.me)


 wechat
Scan Me To Read on Phone
I know you won't do this,but what if you did?