標籤:
這篇是看wklken的《Python進階-Itertools模組小結》 學習itertools模組的學習筆記
在看itertools中各函數的原始碼時,剛開始還比較輕鬆,但後面看起來就比較費勁。。。
1、itertools.count(start=0,step=1)
此函數用來建立一個迭代器,產生從n開始的連續整數,如果忽略n,則從0開始計算
如果超出了sys.maxint,計數器將溢出並繼續行-sys.maxint-1開始計算
定義:
def count(start=0, step=1): #count(10) --> 10, 11, 12, 13..... # count(2.5, 0.5)--> 2.5, 3.0, 3.5 .... n = start while True: yield n n += step
使用:
from itertools import *for i in izip(count(i), [‘a‘, ‘b‘, ‘c‘]): print iout:(1, ‘a‘)(2, ‘b‘)(3, ‘c‘)
2、itertools.cycle(iterable)
建立一個迭代器,對iterable中的元素反覆執行迴圈操作,內部會產生iterable中的元素的一個副本, 次副本用於返回迴圈中的重複項
定義:
def cycle(iterable): # cycle(‘ABCD‘) --> A B C D A B C D .... saved = [] for element in iterable: yield element saved.append(element) while saved: for element in saved: yield element
使用:
from itertools import *i = 0for item in cycle([‘a‘, ‘b‘, ‘c‘]): i += 1 if i == 6: break print (i, item)out:(1, ‘a‘)(2, ‘b‘)(3, ‘c‘)(4, ‘a‘)(5, ‘b‘)
3、itertools.repeat(object[, times])
建立一個迭代器,重複產生object, times (如果已提供) 指定重複計數, 如果未提供times, 將無盡返回該對象
定義:
def repeat(object, times=None): # repeat(10, 3) --> 10, 10, 10 if times is None: while True: yield object else: for i in xrange(time): yield object
使用:
from itertools import *for i in repeat(‘over-and-over‘, 3): print iout:over-and-overover-and-overover-and-over
4、itertools.chain(*iterables)
將多個迭代器作為參數,但只返回單個迭代器,它產生所有參數迭代器的內容,就好像他們來自於一個單一的序列。
定義:
def chain(*iterables): # chain(‘ABC‘, ‘DEF‘) --> A B C D E F for it in iterables: for element in it: yield element
使用:
from itertools import *for i in chain([1, 2, 3], [‘a‘, ‘b‘, ‘c‘]): print iout:123abc
5、itertools.compress(data, selectors)
提供一個挑選清單, 對未經處理資料進行篩選
定義:
def compress(data, selectors): # compress(‘ABCDEF‘, [1, 0, 1, 0, 1, 1]) --> A C E F return (d for d, s in izip(data, selectors) if s)
6、itertools.product(*iterables[, repeat])
笛卡爾積
建立一個迭代器,產生item1, item2等中的項目的笛卡爾積的元組, repeat是一個關鍵字參數,指定重複產生序列的次數。
def product(*args, **kwds): # product(‘ABCD‘, ‘xy‘) --> Ax, Ay, Bx, By, Cx, Cy, Dx, Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get(repeat, 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod)
import itertoolsa = (1, 2, 3)b = (‘a‘, ‘b‘, ‘c‘)c = itertools.product(a, b)for elem in c: print elemout:(1, ‘A‘)(2, ‘B‘)(3, ‘C‘)(2, ‘A‘)(2, ‘B‘)(2, ‘C‘)(3, ‘A‘)(3, ‘B‘)(3, ‘C‘)
這個模組函數有好多,有好多敲了一遍忘了儲存,懶得再敲了,但也記得差不多了,所以就這樣吧
Python學習筆記—itertools模組