python模块之itertools

Python:itertools模块简介

itertools模块包含创建有效迭代器的函数,可以用各种方式对数据进行循环操作,此模块中的所有函数返回的迭代器都可以与for循环语句以及其他包含迭代联合使用。

先来看下该模块包含的方法或函数,然后我们在对其中的部分进行说明

import itertools

print(dir(itertools))
#['__doc__', '__loader__', '__name__', '__package__', '__spec__', '_grouper', '_tee', '_tee_dataobject', 'accumulate', 'chain', 'combinations', 'combinations_with_replacement', 'compress', 'count', 'cycle', 'dropwhile', 'filterfalse', 'groupby', 'islice', 'permutations', 'product', 'repeat', 'starmap', 'takewhile', 'tee', 'zip_longest']

accumulate(iterable[, func])

返回累计和的序列(或其他二元函数结果)。
import itertools

it = itertools.accumulate(range(10))
print(list(it))
#[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]

chain(*iterables)

给出一组迭代器(*iterables),连接多个迭代器,返回的迭代器从*iterables中第0项开始生成项,这一过程会持续到*iterables中所有的项都被用完。

import itertools

it = itertools.chain([1,"ab","hello"])
for i in it:
print(i)
result:
1
ab
hello

chain.from_iterable(iterables):

一个备用链构造函数,其中的iterables是一个迭代变量,生成迭代序列,此操作的结果与以下生成器代码片段生成的结果相同:

import itertools

it = itertools.chain.from_iterable(["1","ab","hello"])
it.__next__()
#”1”

combinations(iterable, r):

创建一个迭代器,返回iterable中所有长度为r的子序列,返回的子序列中的项按输入iterable中的顺序排序:

import itertools

it = itertools.combinations("abcde",3)
for i in it:
print(i)
result:
('a', 'b', 'c')
('a', 'b', 'd')
('a', 'b', 'e')
('a', 'c', 'd')
('a', 'c', 'e')
('a', 'd', 'e')
('b', 'c', 'd')
('b', 'c', 'e')
('b', 'd', 'e')
('c', 'd', 'e')

count([n]):

创建一个迭代器,从起点n开始,"⽆无限" 循环下去,如果忽略n,则从0开始计算(注意:此迭代器不支持长整数),如果超出了sys.maxint,计数器将溢出并继续从-sys.maxint-1开始计算。

import itertools

for x in itertools.count(10,step=2):
    print(x)
if x>17:break
result:
10
12
14
16
18

cycle(iterable):

创建一个迭代器,对iterable中的元素反复执行循环操作,内部会生成iterable中的元素的一个副本,此副本用于返回循环中的重复项。

import itertools

for i,x in enumerate(itertools.cycle("abc")):
    print(i,x)
if i>5:break
result:
0 a
1 b
2 c
3 a
4 b
5 c
6 a

dropwhile(predicate, iterable):

跳过头部符合条件的元素

import itertools

it = itertools.dropwhile(lambda i:i<4,[3,2,7,1,2])
print(list(it))
# [7, 1, 2]

groupby(iterable [,key]):

将连续出现的相同元素进⾏行分组

如果iterable在多次连续迭代中生成了同一项,则会定义一个组,如果将此函数应用一个分类列表,那么分组将定义该列表中的所有唯一项,key(如果已提供)是一个函数,应用于每一项,如果此函数存在返回值,该值将用于后续项而不是该项本身进行比较,此函数返回的迭代器生成元素(key, group),其中key是分组的键值,group是迭代器,生成组成该组的所有项。

import itertools

it1 = [list(k) for k,g in itertools.groupby("aabbbddxxee")]
it2 = [list(g) for k,g in itertools.groupby("aabbbddxxee")]
print(it1)
print(it2)
result:
[['a'], ['b'], ['d'], ['x'], ['e']]
[['a', 'a'], ['b', 'b', 'b'], ['d', 'd'], ['x', 'x'], ['e', 'e']]

ifilterfalse(predicate, iterable):

创建一个迭代器,仅生成iterable中predicate(item)为False的项,如果predicate为None,则返回iterable中所有计算为False的项。

import itertools

it = itertools.filterfalse(lambda x: x%2, range(10))
print(list(it))
# [0, 2, 4, 6, 8]

islice(iterable, [start, ] stop [, step]):

创建一个迭代器,生成项的方式类似于切片返回值: iterable[start : stop : step],将跳过前start个项,迭代在stop所指定的位置停止,step指定用于跳过项的步幅。与切片不同,负值不会用于任何start,stop和step,如果省略了start,迭代将从0开始,如果省略了step,步幅将采用1.

import itertools

it1 = itertools.islice(range(10),3,7)
it2 = itertools.islice(range(10),3,7,2)
print(list(it1))
print(list(it2))
result:
[3, 4, 5, 6]
[3, 5]

zip_longest(iter1, iter2, ... iterN, [fillvalue=None]):

与izip()相同,但是迭代过程会持续到所有输入迭代变量iter1,iter2等都耗尽为止,如果没有使用fillvalue关键字参数指定不同的值,则使用None来填充已经使用的迭代变量的值。

import itertools

it = itertools.zip_longest(range(10),"abc")
print(list(it))
result: [(0, 'a'), (1, 'b'), (2, 'c'), (3, None), (4, None), (5, None), (6, None), (7, None), (8, None), (9, None)]

permutations(iterable [,r]):

创建一个迭代器,返回iterable中所有长度为r的项目序列,如果省略了r,那么序列的长度与iterable中的项目数量相同,与 combinations 顺序组合不同,permutations 让每个元素都从头组合⼀一遍。

import itertools
it1 = itertools.combinations("abc",2)
print(list(it1))
it2 = itertools.permutations("abc",2)
print(list(it2))

result:
[('a', 'b'), ('a', 'c'), ('b', 'c')]
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

product(*iterables, [repeat=1]):

让每个元素都和后⾯面的迭代器完整组合⼀一遍,创建一个迭代器,生成表示item1,item2等中的项目的笛卡尔积的元组,repeat是一个关键字参数,指定重复生成序列的次数。

import itertools

it1 = itertools.product("abc",[1,2,3])
print(list(it1))
result: [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)]

repeat(object [,times]):

创建一个迭代器,重复生成object,times(如果已提供)指定重复计数,如果未提供times,将无止尽返回该对象。

import itertools

it1 = itertools.repeat("abc",3)
print(list(it1))
result: ['abc', 'abc', 'abc']

starmap(func [, iterable]):

按顺序处理每组元素

import itertools

it1 = itertools.starmap(lambda x,y:x+y,((1,4),(10,20)))
print(list(it1))
result: [5, 30]

takewhile(predicate [, iterable]):

创建一个迭代器,生成iterable中predicate(item)为True的项,只要predicate计算为False,迭代就会立即停止。

import itertools

it = itertools.takewhile(lambda i:i<4,[3,2,1,7,1,2])
print(list(it))
# [3, 2, 1]

tee(iterable [, n]):

复制迭代器

import itertools

for i in itertools.tee(range(4),3):
print(list(i))

result:
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3]

原文地址:https://www.cnblogs.com/pinpin/p/10906702.html