Python:itertools模块
itertools模块包含创建有效迭代器的函数,可以用各种方式对数据进行循环操作,此模块中的所有函数返回的迭代器都可以与for循环语句以及其他包含迭代器(如生成器和生成器表达式)的函数联合使用。
chain(iter1, iter2, ..., iterN):
给出一组迭代器(iter1, iter2, ..., iterN),此函数创建一个新迭代器来将所有的迭代器链接起来,返回的迭代器从iter1开始生成项,知道iter1被用完,然后从iter2生成项,这一过程会持续到iterN中所有的项都被用完。
test = chain('AB', 'CDE', 'F') #这里是把所有的连接起来,ABCDEF直接连起来了
for el in test:
print el
A
B
C
D
E
F
1 from itertools import chain
2 test = chain('AB', 'CDE', 'F')
3 for el in test:
4 print el
5
6 A
7 B
8 C
9 D
10 E
11 F
chain.from_iterable(iterables):
一个备用链构造函数,其中的iterables是一个迭代变量,生成迭代序列,此操作的结果与以下生成器代码片段生成的结果相同:
1 >>> def f(iterables):
2 for x in iterables:
3 for y in x:
4 yield y
5
6 >>> test = f('ABCDEF')
7 >>> test.next()
8 'A'
9
10
11 >>> from itertools import chain
12 >>> test = chain.from_iterable('ABCDEF')
13 >>> test.next()
14 'A'
1 >>> def f(iterables):
2 for x in iterables:
3 for y in x:
4 yield y
5
6 >>> test = f('ABCDEF')
7 >>> test.next()
8 'A'
9
10
11 >>> from itertools import chain
12 >>> test = chain.from_iterable('ABCDEF')
13 >>> test.next()
14 'A'
combinations(iterable, r):
创建一个迭代器,返回iterable中所有长度为r的子序列,返回的子序列中的项按输入iterable中的顺序排序:
1 >>> from itertools import combinations
2 >>> test = combinations([1,2,3,4], 2)
3 >>> for el in test:
4 print el
5
6
7 (1, 2)
8 (1, 3)
9 (1, 4)
10 (2, 3)
11 (2, 4)
12 (3, 4)
1 >>> from itertools import combinations
2 >>> test = combinations([1,2,3,4], 2)
3 >>> for el in test:
4 print el
5
6
7 (1, 2)
8 (1, 3)
9 (1, 4)
10 (2, 3)
11 (2, 4)
12 (3, 4)
count([n]):
创建一个迭代器,生成从n开始的连续整数,如果忽略n,则从0开始计算(注意:此迭代器不支持长整数),如果超出了sys.maxint,计数器将溢出并继续从-sys.maxint-1开始计算。
cycle(iterable):
创建一个迭代器,对iterable中的元素反复执行循环操作,内部会生成iterable中的元素的一个副本,此副本用于返回循环中的重复项。
dropwhile(predicate, iterable):
创建一个迭代器,只要函数predicate(item)为True,就丢弃iterable中的项,如果predicate返回False,就会生成iterable中的项和所有后续项。
2 # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
3 iterable = iter(iterable)
4 for x in iterable:
5 if not predicate(x):
6 yield x
7 break
8 for x in iterable:
9 yield x
groupby(iterable [,key]):
创建一个迭代器,对iterable生成的连续项进行分组,在分组过程中会查找重复项。
如果iterable在多次连续迭代中生成了同一项,则会定义一个组,如果将此函数应用一个分类列表,那么分组将定义该列表中的所有唯一 项,key(如果已提供)是一个函数,应用于每一项,如果此函数存在返回值,该值将用于后续项而不是该项本身进行比较,此函数返回的迭代器生成元素 (key, group),其中key是分组的键值,group是迭代器,生成组成该组的所有项。
ifilter(predicate, iterable):
创建一个迭代器,仅生成iterable中predicate(item)为True的项,如果predicate为None,将返回iterable中所有计算为True的项。
ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9
ifilterfalse(predicate, iterable):
创建一个迭代器,仅生成iterable中predicate(item)为False的项,如果predicate为None,则返回iterable中所有计算为False的项。
ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
imap(function, iter1, iter2, iter3, ..., iterN)
创建一个迭代器,生成项function(i1, i2, ..., iN),其中i1,i2...iN分别来自迭代器iter1,iter2 ... iterN,如果function为None,则返回(i1, i2, ..., iN)形式的元组,只要提供的一个迭代器不再生成值,迭代就会停止。
1 >>> from itertools import *
2 >>> d = imap(pow, (2,3,10), (5,2,3))
3 >>> for i in d: print i
4
5 32
6 9
7 1000
8
9 ####
10 >>> d = imap(pow, (2,3,10), (5,2))
11 >>> for i in d: print i
12
13 32
14 9
15
16 ####
17 >>> d = imap(None, (2,3,10), (5,2))
18 >>> for i in d : print i
19
20 (2, 5)
21 (3, 2)
islice(iterable, [start, ] stop [, step]):
创建一个迭代器,生成项的方式类似于切片返回值: iterable[start : stop : step],将跳过前start个项,迭代在stop所指定的位置停止,step指定用于跳过项的步幅。与切片不同,负值不会用于任何start,stop和step,如果省略了start,迭代将从0开始,如果省略了step,步幅将采用1.
# islice('ABCDEFG', 2) --> A B
# islice('ABCDEFG', 2, 4) --> C D
# islice('ABCDEFG', 2, None) --> C D E F G
# islice('ABCDEFG', 0, None, 2) --> A C E G
s = slice(*args)
it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
nexti = next(it)
for i, element in enumerate(iterable):
if i == nexti:
yield element
nexti = next(it)
#If start is None, then iteration starts at zero. If step is None, then the step defaults to one.
15 #Changed in version 2.5: accept None values for default start and step.
izip(iter1, iter2, ... iterN):
创建一个迭代器,生成元组(i1, i2, ... iN),其中i1,i2 ... iN 分别来自迭代器iter1,iter2 ... iterN,只要提供的某个迭代器不再生成值,迭代就会停止,此函数生成的值与内置的zip()函数相同。
1 def izip(*iterables):
2 # izip('ABCD', 'xy') --> Ax By
3 iterables = map(iter, iterables)
4 while iterables:
5 yield tuple(map(next, iterables))
izip_longest(iter1, iter2, ... iterN, [fillvalue=None]):
与izip()相同,但是迭代过程会持续到所有输入迭代变量iter1,iter2等都耗尽为止,如果没有使用fillvalue关键字参数指定不同的值,则使用None来填充已经使用的迭代变量的值。
2 # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
3 fillvalue = kwds.get('fillvalue')
4 def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
5 yield counter() # yields the fillvalue, or raises IndexError
6 fillers = repeat(fillvalue)
7 iters = [chain(it, sentinel(), fillers) for it in args]
8 try:
9 for tup in izip(*iters):
10 yield tup
11 except IndexError:
12 pass
permutations(iterable [,r]):
创建一个迭代器,返回iterable中所有长度为r的项目序列,如果省略了r,那么序列的长度与iterable中的项目数量相同:
2 # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
3 # permutations(range(3)) --> 012 021 102 120 201 210
4 pool = tuple(iterable)
5 n = len(pool)
6 r = n if r is None else r
7 if r > n:
8 return
9 indices = range(n)
10 cycles = range(n, n-r, -1)
11 yield tuple(pool[i] for i in indices[:r])
12 while n:
13 for i in reversed(range(r)):
14 cycles[i] -= 1
15 if cycles[i] == 0:
16 indices[i:] = indices[i+1:] + indices[i:i+1]
17 cycles[i] = n - i
18 else:
19 j = cycles[i]
20 indices[i], indices[-j] = indices[-j], indices[i]
21 yield tuple(pool[i] for i in indices[:r])
22 break
23 else:
24 return
product(iter1, iter2, ... iterN, [repeat=1]):
创建一个迭代器,生成表示item1,item2等中的项目的笛卡尔积的元组,repeat是一个关键字参数,指定重复生成序列的次数。
2 # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
3 # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
4 pools = map(tuple, args) * kwds.get('repeat', 1)
5 result = [[]]
6 for pool in pools:
7 result = [x+[y] for x in result for y in pool]
8 for prod in result:
9 yield tuple(prod)
repeat(object [,times]):
创建一个迭代器,重复生成object,times(如果已提供)指定重复计数,如果未提供times,将无止尽返回该对象。
2 # repeat(10, 3) --> 10 10 10
3 if times is None:
4 while True:
5 yield object
6 else:
7 for i in xrange(times):
8 yield object
starmap(func [, iterable]):
创建一个迭代器,生成值func(*item),其中item来自iterable,只有当iterable生成的项适用于这种调用函数的方式时,此函数才有效。
1 def starmap(function, iterable):
2 # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
3 for args in iterable:
4 yield function(*args)
takewhile(predicate [, iterable]):
创建一个迭代器,生成iterable中predicate(item)为True的项,只要predicate计算为False,迭代就会立即停止。
2 # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
3 for x in iterable:
4 if predicate(x):
5 yield x
6 else:
7 break
tee(iterable [, n]):
从iterable创建n个独立的迭代器,创建的迭代器以n元组的形式返回,n的默认值为2,此函数适用于任何可迭代的对象,但是,为了克隆原始迭代器,生成的项会被缓存,并在所有新创建的迭代器中使用,一定要注意,不要在调用tee()之后使用原始迭代器iterable,否则缓存机制可能无法正确工作。
def tee(iterable, n=2):
it = iter(iterable)
deques = [collections.deque() for i in range(n)]
def gen(mydeque):
while True:
if not mydeque: # when the local deque is empty
newval = next(it) # fetch a new value and
for d in deques: # load it to all the deques
d.append(newval)
yield mydeque.popleft()
return tuple(gen(d) for d in deques) #Once tee() has made a split, the original iterable should not be used anywhere else; otherwise,
the iterable could get advanced without the tee objects being informed.
#This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored).
In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().
def tee(iterable, n=2):
it = iter(iterable)
deques = [collections.deque() for i in range(n)]
def gen(mydeque):
while True:
if not mydeque: # when the local deque is empty
newval = next(it) # fetch a new value and
for d in deques: # load it to all the deques
d.append(newval)
yield mydeque.popleft()
return tuple(gen(d) for d in deques) #Once tee() has made a split, the original iterable should not be used anywhere else; otherwise,
the iterable could get advanced without the tee objects being informed.
#This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored).
In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().
Python:itertools模块的更多相关文章
- 转:Python itertools模块
itertools Python的内建模块itertools提供了非常有用的用于操作迭代对象的函数. 首先,我们看看itertools提供的几个"无限"迭代器: >>& ...
- python, itertools模块
通过itertools模块,可以用各种方式对数据进行循环操作 1, chain() from intertools import chain for i in chain([1,2,3], ('a', ...
- python itertools 模块
Python的内建模块itertools提供了非常有用的用于操作迭代对象的函数 首先,我们看看itertools提供的几个“无限”迭代器: >>> import itertools ...
- python itertools 模块讲解
1.介绍itertools 是python的迭代器模块,itertools提供的工具相当高效且节省内存. 使用这些工具,你将能够创建自己定制的迭代器用于高效率的循环. - 无限迭代器 itertool ...
- python itertools模块练习
参考 <python标准库> 也可以参考Vamei博客 列表用着很舒服,但迭代器不需要将所有数据同时存储在内存中. 本章练习一下python 标准库中itertools模块 合并 和 分解 ...
- Python itertools模块详解
这货很强大, 必须掌握 文档 链接 http://docs.python.org/2/library/itertools.html pymotw 链接 http://pymotw.com/2/iter ...
- [转载] Python itertools模块详解
原文在这里,写的很详细,感谢原作者,以下摘录要点. itertools用于高效循环的迭代函数集合. 无限迭代器 迭代器 参数 结果 例子 count() start, [step] start, st ...
- Python itertools模块中的product函数
product 用于求多个可迭代对象的笛卡尔积(Cartesian Product),它跟嵌套的 for 循环等价.即: product(A, B) 和 ((x,y) for x in A for y ...
- python itertools模块实现排列组合
转自:https://blog.csdn.net/specter11235/article/details/71189486 一.笛卡尔积:itertools.product(*iterables[, ...
- Python标准模块--itertools
1 模块简介 Python提供了itertools模块,可以创建属于自己的迭代器.itertools提供的工具快速并且节约内存.开发者可以使用这些工具创建属于自己特定的迭代器,这些特定的迭代器可以用于 ...
随机推荐
- 通过SQL Server 2008 访问MySQL(转)
在公司中经常会遇到部署多种数据库环境的情况,对于开发人员来说经常在不同数据库之间转换确实有些繁琐,本篇将介绍从SQL Server 操作MySQL 数据库的方法. 数据库测试环境 1. SQL Ser ...
- Debugging with GDB 用GDB调试多线程程序
Debugging with GDB http://www.delorie.com/gnu/docs/gdb/gdb_25.html GDB调试多线程程序总结 一直对GDB多线程调试接触不多,最近因为 ...
- POJ 2193 Lenny's Lucky Lotto Lists (DP)
题目链接 题意 : 给你两个数N和M,让你从1到M中找N个数组成一个序列,这个序列需要满足的条件是后一个数要大于前一个数的两倍,问这样的序列有多少,输出. 思路 : dp[i][j]代表着长度为 i ...
- hdu 2516 取石子游戏 博弈论
很显然的nim游戏的变形,很好找规律 先手败:2,3,5,8,13…… 其他先手胜.即满足菲波拉数列. 代码如下: #include<iostream> #include<stdio ...
- VMware linux与windows文件共享
将要共享的文件做成一个iso文件,然后打开VMware
- UINavigationController使用详解
UINavigationController使用详解 有一阵子没有写随笔,感觉有点儿手生.一个多月以后终于又一次坐下来静下心写随笔,记录自己的学习笔记,也希望能够帮到大家. 废话少说回到正题,UINa ...
- jquery的ajax和原始的ajax这两种方式的使用方法
jquery的ajax是对原始的ajax进行的封装,方便用户的使用.下面用代码分别举例各自的使用方式. jquery的ajax发送和接收xml数据格式. $.ajax({ type: "PU ...
- WM_ACTIVATE
参数: fActive = LOWORD(wParam); // activation flag fMinimized = (BOOL)HIWORD(wParam); // minimized ...
- Retrofit初识
Retrofit Retrofit是一套RESTful架构的Android(Java)客户端实现,基于注解,提供JSON to POJO(Plain Ordinary Java Object,简单Ja ...
- PHP微信公众平台开发1 配置接口
1.简介 微信公众平台是腾讯公司在微信的基础上新增的功能模块,通过这一平台,个人和企业都可以打造一个微信的公众号,并实现和特定群体的文字.图片.语音的全方位沟通.互动. 2.通讯机制 3.注册微信公众 ...