[关闭]
@bergus 2015-12-02T06:45:39.000000Z 字数 18830 阅读 1903

python模块之itertools模块

python python模块 itertools


  1. 迭代器 参数 结果 例子
  2. count() start, [step] start, start+step, start+2*step, ... count(10) --> 10 11 12 13 14 ...
  3. cycle() p p0, p1, ... plast, p0, p1, ... cycle('ABCD') --> A B C D A B C D ...
  4. repeat() elem [,n] elem, elem, elem, ... endlessly or up to n times repeat(10, 3) --> 10 10 10
  5. 处理输入序列迭代器
  6. 迭代器 参数 结果 例子
  7. chain() p, q, ... p0, p1, ... plast, q0, q1, ... chain('ABC', 'DEF') --> A B C D E F
  8. compress() data, selectors (d[0] if s[0]), (d[1] if s[1]), ... compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
  9. dropwhile() pred, seq seq[n], seq[n+1], starting when pred fails dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
  10. groupby() iterable[, keyfunc] sub-iterators grouped by value of keyfunc(v)
  11. ifilter() pred, seq elements of seq where pred(elem) is True ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9
  12. ifilterfalse() pred, seq elements of seq where pred(elem) is False ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
  13. islice() seq, [start,] stop [, step] elements from seq[start:stop:step] islice('ABCDEFG', 2, None) --> C D E F G
  14. imap() func, p, q, ... func(p0, q0), func(p1, q1), ... imap(pow, (2,3,10), (5,2,3)) --> 32 9 1000
  15. starmap() func, seq func(*seq[0]), func(*seq[1]), ... starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
  16. tee() it, n it1, it2 , ... itn splits one iterator into n
  17. takewhile() pred, seq seq[0], seq[1], until pred fails takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
  18. izip() p, q, ... (p[0], q[0]), (p[1], q[1]), ... izip('ABCD', 'xy') --> Ax By
  19. izip_longest() p, q, ... (p[0], q[0]), (p[1], q[1]), ... izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
  20. 组合生成器
  21. 迭代器 参数 结果
  22. product() p, q, ... [repeat=1] cartesian product, equivalent to a nested for-loop
  23. permutations() p[, r] r-length tuples, all possible orderings, no repeated elements
  24. combinations() p, r r-length tuples, in sorted order, no repeated elements
  25. combinations_with_replacement() p, r r-length tuples, in sorted order, with repeated elements
  26. product('ABCD', repeat=2) AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
  27. permutations('ABCD', 2) AB AC AD BA BC BD CA CB CD DA DB DC
  28. combinations('ABCD', 2) AB AC AD BC BD CD
  29. combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD CC CD DD
  30. 第一部分
  31. itertools.count(start=0, step=1)
  32. 创建一个迭代器,生成从n开始的连续整数,如果忽略n,则从0开始计算(注意:此迭代器不支持长整数)
  33. 如果超出了sys.maxint,计数器将溢出并继续从-sys.maxint-1开始计算。
  34. 定义
  35. def count(start=0, step=1):
  36. # count(10) --> 10 11 12 13 14 ...
  37. # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
  38. n = start
  39. while True:
  40. yield n
  41. n += step
  42. 等同于(start + step * i for i in count())
  43. 使用
  44. from itertools import *
  45. for i in izip(count(1), ['a', 'b', 'c']):
  46. print i
  47. (1, 'a')
  48. (2, 'b')
  49. (3, 'c')
  50. itertools.cycle(iterable)
  51. 创建一个迭代器,对iterable中的元素反复执行循环操作,内部会生成iterable中的元素的一个副本,此副本用于返回循环中的重复项。
  52. 定义
  53. def cycle(iterable):
  54. # cycle('ABCD') --> A B C D A B C D A B C D ...
  55. saved = []
  56. for element in iterable:
  57. yield element
  58. saved.append(element)
  59. while saved:
  60. for element in saved:
  61. yield element
  62. 使用
  63. from itertools import *
  64. i = 0
  65. for item in cycle(['a', 'b', 'c']):
  66. i += 1
  67. if i == 10:
  68. break
  69. print (i, item)
  70. (1, 'a')
  71. (2, 'b')
  72. (3, 'c')
  73. (4, 'a')
  74. (5, 'b')
  75. (6, 'c')
  76. (7, 'a')
  77. (8, 'b')
  78. (9, 'c')
  79. itertools.repeat(object[, times])
  80. 创建一个迭代器,重复生成objecttimes(如果已提供)指定重复计数,如果未提供times,将无止尽返回该对象。
  81. 定义
  82. def repeat(object, times=None):
  83. # repeat(10, 3) --> 10 10 10
  84. if times is None:
  85. while True:
  86. yield object
  87. else:
  88. for i in xrange(times):
  89. yield object
  90. 使用
  91. from itertools import *
  92. for i in repeat('over-and-over', 5):
  93. print i
  94. over-and-over
  95. over-and-over
  96. over-and-over
  97. over-and-over
  98. over-and-over
  99. 第二部分
  100. itertools.chain(*iterables)
  101. 将多个迭代器作为参数, 但只返回单个迭代器, 它产生所有参数迭代器的内容, 就好像他们是来自于一个单一的序列.
  102. def chain(*iterables):
  103. # chain('ABC', 'DEF') --> A B C D E F
  104. for it in iterables:
  105. for element in it:
  106. yield element
  107. 使用
  108. from itertools import *
  109. for i in chain([1, 2, 3], ['a', 'b', 'c']):
  110. print i
  111. 1
  112. 2
  113. 3
  114. a
  115. b
  116. c
  117. from itertools import chain, imap
  118. def flatmap(f, items):
  119. return chain.from_iterable(imap(f, items))
  120. >>> list(flatmap(os.listdir, dirs))
  121. >>> ['settings.py', 'wsgi.py', 'templates', 'app.py',
  122. 'templates', 'index.html, 'config.json']
  123. itertools.compress(data, selectors)
  124. 提供一个选择列表,对原始数据进行筛选
  125. def compress(data, selectors):
  126. # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
  127. return (d for d, s in izip(data, selectors) if s)
  128. itertools.dropwhile(predicate, iterable)
  129. 创建一个迭代器,只要函数predicate(item)为True,就丢弃iterable中的项,如果predicate返回False,就会生成iterable中的项和所有后续项。
  130. 即:在条件为false之后的第一次, 返回迭代器中剩下来的项.
  131. def dropwhile(predicate, iterable):
  132. # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
  133. iterable = iter(iterable)
  134. for x in iterable:
  135. if not predicate(x):
  136. yield x
  137. break
  138. for x in iterable:
  139. yield x
  140. 使用
  141. from itertools import *
  142. def should_drop(x):
  143. print 'Testing:', x
  144. return (x<1)
  145. for i in dropwhile(should_drop, [ -1, 0, 1, 2, 3, 4, 1, -2 ]):
  146. print 'Yielding:', i
  147. Testing: -1
  148. Testing: 0
  149. Testing: 1
  150. Yielding: 1
  151. Yielding: 2
  152. Yielding: 3
  153. Yielding: 4
  154. Yielding: 1
  155. Yielding: -2
  156. itertools.groupby(iterable[, key])
  157. 返回一个产生按照key进行分组后的值集合的迭代器.
  158. 如果iterable在多次连续迭代中生成了同一项,则会定义一个组,如果将此函数应用一个分类列表,那么分组将定义该列表中的所有唯一项,key(如果已提供)是一个函数,应用于每一项,如果此函数存在返回值,该值将用于后续项而不是该项本身进行比较,此函数返回的迭代器生成元素(key, group),其中key是分组的键值,group是迭代器,生成组成该组的所有项。
  159. 即:按照keyfunc函数对序列每个元素执行后的结果分组(每个分组是一个迭代器), 返回这些分组的迭代器
  160. 等价于
  161. class groupby(object):
  162. # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
  163. # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
  164. def __init__(self, iterable, key=None):
  165. if key is None:
  166. key = lambda x: x
  167. self.keyfunc = key
  168. self.it = iter(iterable)
  169. self.tgtkey = self.currkey = self.currvalue = object()
  170. def __iter__(self):
  171. return self
  172. def next(self):
  173. while self.currkey == self.tgtkey:
  174. self.currvalue = next(self.it) # Exit on StopIteration
  175. self.currkey = self.keyfunc(self.currvalue)
  176. self.tgtkey = self.currkey
  177. return (self.currkey, self._grouper(self.tgtkey))
  178. def _grouper(self, tgtkey):
  179. while self.currkey == tgtkey:
  180. yield self.currvalue
  181. self.currvalue = next(self.it) # Exit on StopIteration
  182. self.currkey = self.keyfunc(self.currvalue)
  183. 应用
  184. from itertools import groupby
  185. qs = [{'date' : 1},{'date' : 2}]
  186. [(name, list(group)) for name, group in itertools.groupby(qs, lambda p:p['date'])]
  187. Out[77]: [(1, [{'date': 1}]), (2, [{'date': 2}])]
  188. >>> from itertools import *
  189. >>> a = ['aa', 'ab', 'abc', 'bcd', 'abcde']
  190. >>> for i, k in groupby(a, len):
  191. ... print i, list(k)
  192. ...
  193. 2 ['aa', 'ab']
  194. 3 ['abc', 'bcd']
  195. 5 ['abcde']
  196. 另一个例子
  197. from itertools import *
  198. from operator import itemgetter
  199. d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
  200. di = sorted(d.iteritems(), key=itemgetter(1))
  201. for k, g in groupby(di, key=itemgetter(1)):
  202. print k, map(itemgetter(0), g)
  203. 1 ['a', 'c', 'e']
  204. 2 ['b', 'd', 'f']
  205. 3 ['g']
  206. itertools.ifilter(predicate, iterable)
  207. 返回的是迭代器类似于针对列表的内置函数 filter() , 它只包括当测试函数返回true时的项. 它不同于 dropwhile()
  208. 创建一个迭代器,仅生成iterable中predicate(item)为True的项,如果predicate为None,将返回iterable中所有计算为True的项
  209. 对函数func执行返回真的元素的迭代器
  210. def ifilter(predicate, iterable):
  211. # ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9
  212. if predicate is None:
  213. predicate = bool
  214. for x in iterable:
  215. if predicate(x):
  216. yield x
  217. 使用
  218. from itertools import *
  219. def check_item(x):
  220. print 'Testing:', x
  221. return (x<1)
  222. for i in ifilter(check_item, [ -1, 0, 1, 2, 3, 4, 1, -2 ]):
  223. print 'Yielding:', i
  224. Testing: -1
  225. Yielding: -1
  226. Testing: 0
  227. Yielding: 0
  228. Testing: 1
  229. Testing: 2
  230. Testing: 3
  231. Testing: 4
  232. Testing: 1
  233. Testing: -2
  234. Yielding: -2
  235. itertools.ifilterfalse(predicate, iterable)
  236. 和ifilter(函数相反 , 返回一个包含那些测试函数返回false的项的迭代器)
  237. 创建一个迭代器,仅生成iterable中predicate(item)为False的项,如果predicate为None,则返回iterable中所有计算为False的项 对函数func执行返回假的元素的迭代器
  238. def ifilterfalse(predicate, iterable):
  239. # ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
  240. if predicate is None:
  241. predicate = bool
  242. for x in iterable:
  243. if not predicate(x):
  244. yield x
  245. 使用
  246. from itertools import *
  247. def check_item(x):
  248. print 'Testing:', x
  249. return (x<1)
  250. for i in ifilterfalse(check_item, [ -1, 0, 1, 2, 3, 4, 1, -2 ]):
  251. print 'Yielding:', i
  252. Testing: -1
  253. Testing: 0
  254. Testing: 1
  255. Yielding: 1
  256. Testing: 2
  257. Yielding: 2
  258. Testing: 3
  259. Yielding: 3
  260. Testing: 4
  261. Yielding: 4
  262. Testing: 1
  263. Yielding: 1
  264. Testing: -2
  265. itertools.islice(iterable, stop)
  266. itertools.islice(iterable, start, stop[, step])
  267. 返回的迭代器是返回了输入迭代器根据索引来选取的项
  268. 创建一个迭代器,生成项的方式类似于切片返回值: iterable[start : stop : step],将跳过前start个项,迭代在stop所指定的位置停止,step指定用于跳过项的步幅。 与切片不同,负值不会用于任何start,stop和step, 如果省略了start,迭代将从0开始,如果省略了step,步幅将采用1.
  269. 返回序列seq的从start开始到stop结束的步长为step的元素的迭代器
  270. def islice(iterable, *args):
  271. # islice('ABCDEFG', 2) --> A B
  272. # islice('ABCDEFG', 2, 4) --> C D
  273. # islice('ABCDEFG', 2, None) --> C D E F G
  274. # islice('ABCDEFG', 0, None, 2) --> A C E G
  275. s = slice(*args)
  276. it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
  277. nexti = next(it)
  278. for i, element in enumerate(iterable):
  279. if i == nexti:
  280. yield element
  281. nexti = next(it)
  282. 使用
  283. from itertools import *
  284. print 'Stop at 5:'
  285. for i in islice(count(), 5):
  286. print i
  287. print 'Start at 5, Stop at 10:'
  288. for i in islice(count(), 5, 10):
  289. print i
  290. print 'By tens to 100:'
  291. for i in islice(count(), 0, 100, 10):
  292. print i
  293. Stop at 5:
  294. 0
  295. 1
  296. 2
  297. 3
  298. 4
  299. Start at 5, Stop at 10:
  300. 5
  301. 6
  302. 7
  303. 8
  304. 9
  305. By tens to 100:
  306. 0
  307. 10
  308. 20
  309. 30
  310. 40
  311. 50
  312. 60
  313. 70
  314. 80
  315. 90
  316. itertools.imap(function, *iterables)
  317. 创建一个迭代器,生成项function(i1, i2, ..., iN),其中i1,i2...iN分别来自迭代器iter1,iter2 ... iterN,如果function为None,则返回(i1, i2, ..., iN)形式的元组,只要提供的一个迭代器不再生成值,迭代就会停止。
  318. 即:返回一个迭代器, 它是调用了一个其值在输入迭代器上的函数, 返回结果. 它类似于内置函数 map() , 只是前者在任意输入迭代器结束后就停止(而不是插入None值来补全所有的输入).
  319. 返回序列每个元素被func执行后返回值的序列的迭代器
  320. def imap(function, *iterables):
  321. # imap(pow, (2,3,10), (5,2,3)) --> 32 9 1000
  322. iterables = map(iter, iterables)
  323. while True:
  324. args = [next(it) for it in iterables]
  325. if function is None:
  326. yield tuple(args)
  327. else:
  328. yield function(*args)
  329. 使用
  330. from itertools import *
  331. print 'Doubles:'
  332. for i in imap(lambda x:2*x, xrange(5)):
  333. print i
  334. print 'Multiples:'
  335. for i in imap(lambda x,y:(x, y, x*y), xrange(5), xrange(5,10)):
  336. print '%d * %d = %d' % i
  337. Doubles:
  338. 0
  339. 2
  340. 4
  341. 6
  342. 8
  343. Multiples:
  344. 0 * 5 = 0
  345. 1 * 6 = 6
  346. 2 * 7 = 14
  347. 3 * 8 = 24
  348. 4 * 9 = 36
  349. itertools.starmap(function, iterable)
  350. 创建一个迭代器,生成值func(*item),其中item来自iterable,只有当iterable生成的项适用于这种调用函数的方式时,此函数才有效。
  351. 对序列seq的每个元素作为func的参数列表执行, 返回执行结果的迭代器
  352. def starmap(function, iterable):
  353. # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
  354. for args in iterable:
  355. yield function(*args)
  356. 使用
  357. from itertools import *
  358. values = [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)]
  359. for i in starmap(lambda x,y:(x, y, x*y), values):
  360. print '%d * %d = %d' % i
  361. 0 * 5 = 0
  362. 1 * 6 = 6
  363. 2 * 7 = 14
  364. 3 * 8 = 24
  365. 4 * 9 = 36
  366. itertools.tee(iterable[, n=2])
  367. 返回一些基于单个原始输入的独立迭代器(默认为2). 它和Unix上的tee工具有点语义相似, 也就是说它们都重复读取输入设备中的值并将值写入到一个命名文件和标准输出中
  368. 从iterable创建n个独立的迭代器,创建的迭代器以n元组的形式返回,n的默认值为2,此函数适用于任何可迭代的对象,但是,为了克隆原始迭代器,生成的项会被缓存,并在所有新创建的迭代器中使用,一定要注意,不要在调用tee()之后使用原始迭代器iterable,否则缓存机制可能无法正确工作。
  369. 把一个迭代器分为n个迭代器, 返回一个元组.默认是两个
  370. def tee(iterable, n=2):
  371. it = iter(iterable)
  372. deques = [collections.deque() for i in range(n)]
  373. def gen(mydeque):
  374. while True:
  375. if not mydeque: # when the local deque is empty
  376. newval = next(it) # fetch a new value and
  377. for d in deques: # load it to all the deques
  378. d.append(newval)
  379. yield mydeque.popleft()
  380. return tuple(gen(d) for d in deques)
  381. 使用
  382. from itertools import *
  383. r = islice(count(), 5)
  384. i1, i2 = tee(r)
  385. for i in i1:
  386. print 'i1:', i
  387. for i in i2:
  388. print 'i2:', i
  389. i1: 0
  390. i1: 1
  391. i1: 2
  392. i1: 3
  393. i1: 4
  394. i2: 0
  395. i2: 1
  396. i2: 2
  397. i2: 3
  398. i2: 4
  399. itertools.takewhile(predicate, iterable)
  400. 和dropwhile相反
  401. 创建一个迭代器,生成iterable中predicate(item)为True的项,只要predicate计算为False,迭代就会立即停止。
  402. 即:从序列的头开始, 直到执行函数func失败.
  403. def takewhile(predicate, iterable):
  404. # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
  405. for x in iterable:
  406. if predicate(x):
  407. yield x
  408. else:
  409. break
  410. 使用
  411. from itertools import *
  412. def should_take(x):
  413. print 'Testing:', x
  414. return (x<2)
  415. for i in takewhile(should_take, [ -1, 0, 1, 2, 3, 4, 1, -2 ]):
  416. print 'Yielding:', i
  417. Testing: -1
  418. Yielding: -1
  419. Testing: 0
  420. Yielding: 0
  421. Testing: 1
  422. Yielding: 1
  423. Testing: 2
  424. itertools.izip(*iterables)
  425. 返回一个合并了多个迭代器为一个元组的迭代器. 它类似于内置函数zip(), 只是它返回的是一个迭代器而不是一个列表
  426. 创建一个迭代器,生成元组(i1, i2, ... iN),其中i1,i2 ... iN 分别来自迭代器iter1,iter2 ... iterN,只要提供的某个迭代器不再生成值,迭代就会停止,此函数生成的值与内置的zip()函数相同。
  427. izip(iter1, iter2, ... iterN):
  428. 返回:(it1[0],it2 [0], it3[0], ..), (it1[1], it2[1], it3[1], ..)...
  429. def izip(*iterables):
  430. # izip('ABCD', 'xy') --> Ax By
  431. iterators = map(iter, iterables)
  432. while iterators:
  433. yield tuple(map(next, iterators))
  434. 使用
  435. from itertools import *
  436. for i in izip([1, 2, 3], ['a', 'b', 'c']):
  437. print i
  438. (1, 'a')
  439. (2, 'b')
  440. (3, 'c')
  441. itertools.izip_longest(*iterables[, fillvalue])
  442. 与izip()相同,但是迭代过程会持续到所有输入迭代变量iter1,iter2等都耗尽为止,如果没有使用fillvalue关键字参数指定不同的值,则使用None来填充已经使用的迭代变量的值。
  443. class ZipExhausted(Exception):
  444. pass
  445. def izip_longest(*args, **kwds):
  446. # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
  447. fillvalue = kwds.get('fillvalue')
  448. counter = [len(args) - 1]
  449. def sentinel():
  450. if not counter[0]:
  451. raise ZipExhausted
  452. counter[0] -= 1
  453. yield fillvalue
  454. fillers = repeat(fillvalue)
  455. iterators = [chain(it, sentinel(), fillers) for it in args]
  456. try:
  457. while iterators:
  458. yield tuple(map(next, iterators))
  459. except ZipExhausted:
  460. pass
  461. 第三部分
  462. itertools.product(*iterables[, repeat])
  463. 笛卡尔积
  464. 创建一个迭代器,生成表示item1,item2等中的项目的笛卡尔积的元组,repeat是一个关键字参数,指定重复生成序列的次数。
  465. def product(*args, **kwds):
  466. # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
  467. # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
  468. pools = map(tuple, args) * kwds.get('repeat', 1)
  469. result = [[]]
  470. for pool in pools:
  471. result = [x+[y] for x in result for y in pool]
  472. for prod in result:
  473. yield tuple(prod)
  474. 例子
  475. import itertools
  476. a = (1, 2, 3)
  477. b = ('A', 'B', 'C')
  478. c = itertools.product(a,b)
  479. for elem in c:
  480. print elem
  481. (1, 'A')
  482. (1, 'B')
  483. (1, 'C')
  484. (2, 'A')
  485. (2, 'B')
  486. (2, 'C')
  487. (3, 'A')
  488. (3, 'B')
  489. (3, 'C')
  490. itertools.permutations(iterable[, r])
  491. 排列
  492. 创建一个迭代器,返回iterable中所有长度为r的项目序列,如果省略了r,那么序列的长度与iterable中的项目数量相同: 返回p中任意取r个元素做排列的元组的迭代器
  493. def permutations(iterable, r=None):
  494. # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
  495. # permutations(range(3)) --> 012 021 102 120 201 210
  496. pool = tuple(iterable)
  497. n = len(pool)
  498. r = n if r is None else r
  499. if r > n:
  500. return
  501. indices = range(n)
  502. cycles = range(n, n-r, -1)
  503. yield tuple(pool[i] for i in indices[:r])
  504. while n:
  505. for i in reversed(range(r)):
  506. cycles[i] -= 1
  507. if cycles[i] == 0:
  508. indices[i:] = indices[i+1:] + indices[i:i+1]
  509. cycles[i] = n - i
  510. else:
  511. j = cycles[i]
  512. indices[i], indices[-j] = indices[-j], indices[i]
  513. yield tuple(pool[i] for i in indices[:r])
  514. break
  515. else:
  516. return
  517. 也可以用product实现
  518. def permutations(iterable, r=None):
  519. pool = tuple(iterable)
  520. n = len(pool)
  521. r = n if r is None else r
  522. for indices in product(range(n), repeat=r):
  523. if len(set(indices)) == r:
  524. yield tuple(pool[i] for i in indices)
  525. itertools.combinations(iterable, r)
  526. 创建一个迭代器,返回iterable中所有长度为r的子序列,返回的子序列中的项按输入iterable中的顺序排序 (不带重复)
  527. def combinations(iterable, r):
  528. # combinations('ABCD', 2) --> AB AC AD BC BD CD
  529. # combinations(range(4), 3) --> 012 013 023 123
  530. pool = tuple(iterable)
  531. n = len(pool)
  532. if r > n:
  533. return
  534. indices = range(r)
  535. yield tuple(pool[i] for i in indices)
  536. while True:
  537. for i in reversed(range(r)):
  538. if indices[i] != i + n - r:
  539. break
  540. else:
  541. return
  542. indices[i] += 1
  543. for j in range(i+1, r):
  544. indices[j] = indices[j-1] + 1
  545. yield tuple(pool[i] for i in indices)
  546. #或者
  547. def combinations(iterable, r):
  548. pool = tuple(iterable)
  549. n = len(pool)
  550. for indices in permutations(range(n), r):
  551. if sorted(indices) == list(indices):
  552. yield tuple(pool[i] for i in indices)
  553. itertools.combinations_with_replacement(iterable, r)
  554. 创建一个迭代器,返回iterable中所有长度为r的子序列,返回的子序列中的项按输入iterable中的顺序排序 (带重复)
  555. def combinations_with_replacement(iterable, r):
  556. # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
  557. pool = tuple(iterable)
  558. n = len(pool)
  559. if not n and r:
  560. return
  561. indices = [0] * r
  562. yield tuple(pool[i] for i in indices)
  563. while True:
  564. for i in reversed(range(r)):
  565. if indices[i] != n - 1:
  566. break
  567. else:
  568. return
  569. indices[i:] = [indices[i] + 1] * (r - i)
  570. yield tuple(pool[i] for i in indices)
  571. 或者
  572. def combinations_with_replacement(iterable, r):
  573. pool = tuple(iterable)
  574. n = len(pool)
  575. for indices in product(range(n), repeat=r):
  576. if sorted(indices) == list(indices):
  577. yield tuple(pool[i] for i in indices)
  578. 第四部分
  579. 扩展
  580. 使用现有扩展功能
  581. def take(n, iterable):
  582. "Return first n items of the iterable as a list"
  583. return list(islice(iterable, n))
  584. def tabulate(function, start=0):
  585. "Return function(0), function(1), ..."
  586. return imap(function, count(start))
  587. def consume(iterator, n):
  588. "Advance the iterator n-steps ahead. If n is none, consume entirely."
  589. # Use functions that consume iterators at C speed.
  590. if n is None:
  591. # feed the entire iterator into a zero-length deque
  592. collections.deque(iterator, maxlen=0)
  593. else:
  594. # advance to the empty slice starting at position n
  595. next(islice(iterator, n, n), None)
  596. def nth(iterable, n, default=None):
  597. "Returns the nth item or a default value"
  598. return next(islice(iterable, n, None), default)
  599. def quantify(iterable, pred=bool):
  600. "Count how many times the predicate is true"
  601. return sum(imap(pred, iterable))
  602. def padnone(iterable):
  603. """Returns the sequence elements and then returns None indefinitely.
  604. Useful for emulating the behavior of the built-in map() function.
  605. """
  606. return chain(iterable, repeat(None))
  607. def ncycles(iterable, n):
  608. "Returns the sequence elements n times"
  609. return chain.from_iterable(repeat(tuple(iterable), n))
  610. def dotproduct(vec1, vec2):
  611. return sum(imap(operator.mul, vec1, vec2))
  612. def flatten(listOfLists):
  613. "Flatten one level of nesting"
  614. return chain.from_iterable(listOfLists)
  615. def repeatfunc(func, times=None, *args):
  616. """Repeat calls to func with specified arguments.
  617. Example: repeatfunc(random.random)
  618. """
  619. if times is None:
  620. return starmap(func, repeat(args))
  621. return starmap(func, repeat(args, times))
  622. def pairwise(iterable):
  623. "s -> (s0,s1), (s1,s2), (s2, s3), ..."
  624. a, b = tee(iterable)
  625. next(b, None)
  626. return izip(a, b)
  627. def grouper(iterable, n, fillvalue=None):
  628. "Collect data into fixed-length chunks or blocks"
  629. # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
  630. args = [iter(iterable)] * n
  631. return izip_longest(fillvalue=fillvalue, *args)
  632. def roundrobin(*iterables):
  633. "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
  634. # Recipe credited to George Sakkis
  635. pending = len(iterables)
  636. nexts = cycle(iter(it).next for it in iterables)
  637. while pending:
  638. try:
  639. for next in nexts:
  640. yield next()
  641. except StopIteration:
  642. pending -= 1
  643. nexts = cycle(islice(nexts, pending))
  644. def powerset(iterable):
  645. "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
  646. s = list(iterable)
  647. return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
  648. def unique_everseen(iterable, key=None):
  649. "List unique elements, preserving order. Remember all elements ever seen."
  650. # unique_everseen('AAAABBBCCDAABBB') --> A B C D
  651. # unique_everseen('ABBCcAD', str.lower) --> A B C D
  652. seen = set()
  653. seen_add = seen.add
  654. if key is None:
  655. for element in ifilterfalse(seen.__contains__, iterable):
  656. seen_add(element)
  657. yield element
  658. else:
  659. for element in iterable:
  660. k = key(element)
  661. if k not in seen:
  662. seen_add(k)
  663. yield element
  664. def unique_justseen(iterable, key=None):
  665. "List unique elements, preserving order. Remember only the element just seen."
  666. # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
  667. # unique_justseen('ABBCcAD', str.lower) --> A B C A D
  668. return imap(next, imap(itemgetter(1), groupby(iterable, key)))
  669. def iter_except(func, exception, first=None):
  670. """ Call a function repeatedly until an exception is raised.
  671. Converts a call-until-exception interface to an iterator interface.
  672. Like __builtin__.iter(func, sentinel) but uses an exception instead
  673. of a sentinel to end the loop.
  674. Examples:
  675. bsddbiter = iter_except(db.next, bsddb.error, db.first)
  676. heapiter = iter_except(functools.partial(heappop, h), IndexError)
  677. dictiter = iter_except(d.popitem, KeyError)
  678. dequeiter = iter_except(d.popleft, IndexError)
  679. queueiter = iter_except(q.get_nowait, Queue.Empty)
  680. setiter = iter_except(s.pop, KeyError)
  681. """
  682. try:
  683. if first is not None:
  684. yield first()
  685. while 1:
  686. yield func()
  687. except exception:
  688. pass
  689. def random_product(*args, **kwds):
  690. "Random selection from itertools.product(*args, **kwds)"
  691. pools = map(tuple, args) * kwds.get('repeat', 1)
  692. return tuple(random.choice(pool) for pool in pools)
  693. def random_permutation(iterable, r=None):
  694. "Random selection from itertools.permutations(iterable, r)"
  695. pool = tuple(iterable)
  696. r = len(pool) if r is None else r
  697. return tuple(random.sample(pool, r))
  698. def random_combination(iterable, r):
  699. "Random selection from itertools.combinations(iterable, r)"
  700. pool = tuple(iterable)
  701. n = len(pool)
  702. indices = sorted(random.sample(xrange(n), r))
  703. return tuple(pool[i] for i in indices)
  704. def random_combination_with_replacement(iterable, r):
  705. "Random selection from itertools.combinations_with_replacement(iterable, r)"
  706. pool = tuple(iterable)
  707. n = len(pool)
  708. indices = sorted(random.randrange(n) for i in xrange(r))
  709. return tuple(pool[i] for i in indices)
  710. def tee_lookahead(t, i):
  711. """Inspect the i-th upcomping value from a tee object
  712. while leaving the tee object at its current position.
  713. Raise an IndexError if the underlying iterator doesn't
  714. have enough values.
  715. """
  716. for value in islice(t.__copy__(), i, None):
  717. return value
  718. raise IndexError(i)
  719. 自定义扩展
  720. 将序列按大小切分,更好的性能
  721. from itertools import chain, islice
  722. def chunks(iterable, size, format=iter):
  723. it = iter(iterable)
  724. while True:
  725. yield format(chain((it.next(),), islice(it, size - 1)))
  726. >>> l = ["a", "b", "c", "d", "e", "f", "g"]
  727. >>> for chunk in chunks(l, 3, tuple):...
  728. print chunk...
  729. ("a", "b", "c")
  730. ("d", "e", "f")
  731. ("g",)
  732. 补充
  733. 迭代工具,你最好的朋友
  734. 迭代工具模块包含了操做指定的函数用于操作迭代器。想复制一个迭代器出来?链接两个迭代器?以one liner(这里的one-liner只需一行代码能搞定的任务)用内嵌的列表组合一组值?不使用list创建Map/Zip?···,你要做的就是 import itertools,举个例子吧:
  735. 四匹马赛跑到达终点排名的所有可能性:
  736. >>> horses = [1, 2, 3, 4]
  737. >>> races = itertools.permutations(horses)
  738. >>> print(races)
  739. <itertools.permutations object at 0xb754f1dc]]>
  740. >>> print(list(itertools.permutations(horses)))
  741. [(1, 2, 3, 4),
  742. (1, 2, 4, 3),
  743. (1, 3, 2, 4),
  744. (1, 3, 4, 2),
  745. (1, 4, 2, 3),
  746. (1, 4, 3, 2),
  747. (2, 1, 3, 4),
  748. (2, 1, 4, 3),
  749. (2, 3, 1, 4),
  750. (2, 3, 4, 1),
  751. (2, 4, 1, 3),
  752. (2, 4, 3, 1),
  753. (3, 1, 2, 4),
  754. (3, 1, 4, 2),
  755. (3, 2, 1, 4),
  756. (3, 2, 4, 1),
  757. (3, 4, 1, 2),
  758. (3, 4, 2, 1),
  759. (4, 1, 2, 3),
  760. (4, 1, 3, 2),
  761. (4, 2, 1, 3),
  762. (4, 2, 3, 1),
  763. (4, 3, 1, 2),
  764. (4, 3, 2, 1)]
  765. 理解迭代的内部机制: 迭代(iteration)就是对可迭代对象(iterables,实现了__iter__()方法)和迭代器(iterators,实现了__next__()方法)的一个操作过程。可迭代对象是任何可返回一个迭代器的对象,迭代器是应用在迭代对象中迭代的对象,换一种方式说的话就是:iterable对象的__iter__()方法可以返回iterator对象,iterator通过调用next()方法获取其中的每一个值(译者注),读者可以结合Java API中的 Iterable接口和Iterator接口进行类比。
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注