對python中的高效迭代器函數(shù)詳解
python中內(nèi)置的庫中有個itertools,可以滿足我們在編程中絕大多數(shù)需要迭代的場合,當(dāng)然也可以自己造輪子,但是有現(xiàn)成的好用的輪子不妨也學(xué)習(xí)一下,看哪個用的順手~
首先還是要先import一下:
#import itertools from itertools import * #最好使用時用上面那個,不過下面的是為了演示比較 常用的,所以就直接全部導(dǎo)入了
一.無限迭代器:
由于這些都是無限迭代器,因此使用的時候都要設(shè)置終止條件,不然會一直運行下去,也就不是我們想要的結(jié)果了。
1、count()
可以設(shè)置兩個參數(shù),第一個參數(shù)為起始點,且包含在內(nèi),第二個參數(shù)為步長,如果不設(shè)置第二個參數(shù)則默認步長為1
for x in count(10,20): if x < 200: print x
def count(start=0, step=1): # count(10) --> 10 11 12 13 14 ... # count(2.5, 0.5) -> 2.5 3.0 3.5 ... n = start while True: yield n n += step
2、cycle()
可以設(shè)置一個參數(shù),且只接受可以迭代的參數(shù),如列表,元組,字符串。。。,該函數(shù)會對可迭代的所有元素進行循環(huán):
for i,x in enumerate(cycle('abcd')): if i < 5: print x
def cycle(iterable): # cycle('ABCD') --> A B C D 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
3、repeat()
可以設(shè)置兩個參數(shù),其中第一個參數(shù)要求可迭代,第二個參數(shù)為重復(fù)次數(shù),第二個參數(shù)如不設(shè)置則無限循環(huán),一般來說使用時都會設(shè)置第二個參數(shù),用來滿足預(yù)期重復(fù)次數(shù)后終止:
#注意如果不設(shè)置第二個參數(shù)notebook運行可能會宕機 for x in repeat(['a','b','c'],10): print x
二.有限迭代器
1、chain()
可以接受不定個數(shù)個可迭代參數(shù),不要求可迭代參數(shù)類型相同,會返回一個列表,這個類似于list的extend,不過不同點是list的extend是對原變量進行改變不返回,而chain則是就地改變并返回:
list(chain(range(4),range(5))) list(chain(range(4),'abc')) list(chain(('a','b','c'),'nihao',['shijie','zhongguo']))
def chain(*iterables): # chain('ABC', 'DEF') --> A B C D E F for it in iterables: for element in it: yield element
2.compress()
第一個參數(shù)為可迭代類型,第二個參數(shù)為0和1的集合,兩者長度可以不等,
這個暫時不知道可以用在哪里、
list(compress(['a','b','c','d','e'],[0,1,1,1,0,1]))
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)
3.dropwhile()
接受兩個參數(shù),第一個參數(shù)為一個判斷類似于if語句的函數(shù),丟棄滿足的項,直到第一個不滿足的項出現(xiàn)時停止丟棄,就是
#偽代碼大概是這個樣子的 if condition: drop element while not condition: stop drop
list(dropwhile(lambda x:x>5,range(10,0,-1)))
def dropwhile(predicate, iterable): # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1 iterable = iter(iterable) for x in iterable: if not predicate(x): yield x break for x in iterable: yield x
4.groupby
對給定可迭代集合(有重復(fù)元素)進行分組,返回的是一個元組,元組的第一個為分組的元素,第二個為分組的元素集合,還是看代碼吧:
for x,y in groupby(['a','a','b','b','b','b','c','d','e','e']): print x print list(y) print '' out: a ['a', 'a'] b ['b', 'b', 'b', 'b'] c ['c'] d ['d'] e ['e', 'e']
class groupby(object): # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D def __init__(self, iterable, key=None): if key is None: key = lambda x: x self.keyfunc = key self.it = iter(iterable) self.tgtkey = self.currkey = self.currvalue = object() def __iter__(self): return self def next(self): while self.currkey == self.tgtkey: self.currvalue = next(self.it) # Exit on StopIteration self.currkey = self.keyfunc(self.currvalue) self.tgtkey = self.currkey return (self.currkey, self._grouper(self.tgtkey)) def _grouper(self, tgtkey): while self.currkey == tgtkey: yield self.currvalue self.currvalue = next(self.it) # Exit on StopIteration self.currkey = self.keyfunc(self.currvalue)
5.ifilter()
這個有點像是filter函數(shù)了,不過有點不同,filter返回的是一個完成后的列表,而ifilter則是一個生成器,使用的yield
#這樣寫只是為了更清楚看到輸出,其實這么寫就跟filter用法一樣了,體現(xiàn)不到ifilter的優(yōu)越之處了 list(ifilter(lambda x:x%2,range(10)))
6.ifilterfalse()
這個跟ifilter用法很像,只是兩個是相反數(shù)的關(guān)系。
list(ifilterfalse(lambda x:x%2,range(10)))
7.islice()
接受三個參數(shù),可迭代參數(shù),起始切片點,結(jié)束切片點,最少給定兩個參數(shù),當(dāng)只有兩個參數(shù)為默認第二個參數(shù)為結(jié)束切片點:
In: list(islice(range(10),2,None)) Out: [2, 3, 4, 5, 6, 7, 8, 9] In: list(islice(range(10),2)) Out: [0, 1]
8.imap()
接受參數(shù)個數(shù)跟目標(biāo)函數(shù)有關(guān):
#接受兩個參數(shù)時 list(imap(abs,range(-5,5))) #接受三個參數(shù)時 list(imap(pow,range(-5,5),range(10))) #接受四個參數(shù)時 list(imap(lambda x,y,z:x+y+z,range(10),range(10),range(10)))
9.starmap()
這個是imap的變異,即只接受兩個參數(shù),目標(biāo)函數(shù)會作用在第二個參數(shù)集合中、
in: list(starmap(pow,[(1,2),(2,3)])) out: [1, 8]
10.tee()
接受兩個參數(shù),第一個參數(shù)為可迭代類型,第二個為int,如果第二個不指定則默認為2,即重復(fù)兩次,有點像是生成器repeat的生成器類型,
這個就有意思了,是雙重生成器輸出:
for x in list(tee('abcde',3)): print list(x)
11.takewhile()
這個有點跟dropwhile()很是想象,一個是丟棄,一個是拿?。?/p>
偽代碼為:
if condition: take this element while not condition: stop take
eg:
in: list(takewhile(lambda x:x<10,(1,9,10,11,8))) out: [1, 9]
12.izip()
這個跟imap一樣,只不過imap是針對map的生成器類型,而izip是針對zip的:
list(izip('ab','cd'))
13.izip_longest
針對izip只截取最短的,這個是截取最長的,以None來填充空位:
list(izip_longest('a','abcd'))
三、組合迭代器
1.product()
這個有點像是多次使用for循環(huán),兩者可以替代。
list(product(range(10),range(10))) #本質(zhì)上是這種的生成器模式 L = [] for x in range(10): for y in range(10): L.append((x,y))
2.permutations()
接受兩個參數(shù),第二個參數(shù)不設(shè)置時輸出的沒看出來是什么鬼,
第二個參數(shù)用來控制生成的元組的元素個數(shù),而輸出的元組中最后一個元素是打亂次序的,暫時也不知道可以用在哪
list(permutations(range(10),2))
3.combinations()
用來排列組合,抽樣不放回,第二個參數(shù)為參與排列組合的個數(shù)
list(combinations('abc',2))
def combinations(iterable, r): # combinations('ABCD', 2) --> AB AC AD BC BD CD # combinations(range(4), 3) --> 012 013 023 123 pool = tuple(iterable) n = len(pool) if r > n: return indices = range(r) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices)
def combinations(iterable, r): pool = tuple(iterable) n = len(pool) for indices in permutations(range(n), r): if sorted(indices) == list(indices): yield tuple(pool[i] for i in indices)
4.combinations_with_replacement()
與上一個的用法不同的是抽樣是放回的
def combinations_with_replacement(iterable, r): # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC pool = tuple(iterable) n = len(pool) if not n and r: return indices = [0] * r yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != n - 1: break else: return indices[i:] = [indices[i] + 1] * (r - i) yield tuple(pool[i] for i in indices)
def combinations_with_replacement(iterable, r): pool = tuple(iterable) n = len(pool) for indices in product(range(n), repeat=r): if sorted(indices) == list(indices): yield tuple(pool[i] for i in indices)
以上這篇對python中的高效迭代器函數(shù)詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Django與數(shù)據(jù)庫交互的實現(xiàn)
最近在學(xué)習(xí)Django,本文主要介紹了Django與數(shù)據(jù)庫交互的實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06python導(dǎo)出chrome書簽到markdown文件的實例代碼
python導(dǎo)出chrome書簽到markdown文件,主要就是解析chrome的bookmarks文件,然后拼接成markdown格式的字符串,最后輸出到文件即可。下面給大家分享實例代碼,需要的朋友參考下2017-12-12Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)篩選及提取序列中元素的方法
這篇文章主要介紹了Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)篩選及提取序列中元素的方法,涉及Python列表推導(dǎo)式、生成器表達式及filter()函數(shù)相關(guān)使用技巧,需要的朋友可以參考下2018-03-03python程序運行添加命令行參數(shù)argparse模塊具體用法詳解
這篇文章主要給大家介紹了關(guān)于python程序運行添加命令行參數(shù)argparse模塊具體用法的相關(guān)資料,argparse是Python內(nèi)置的一個用于命令項選項與參數(shù)解析的模塊,通過在程序中定義好我們需要的參數(shù),需要的朋友可以參考下2024-01-01Python利用hashlib實現(xiàn)文件MD5碼的批量存儲
這篇文章主要為大家詳細介紹了如何用Python和hashlib實現(xiàn)文件MD5碼的批量存儲功能,文中的示例代碼講解詳細,感興趣的小伙伴可以學(xué)習(xí)一下2023-05-05Python生成指定數(shù)量的優(yōu)惠碼實操內(nèi)容
在本篇文章里小編給大家整理了關(guān)于Python生成指定數(shù)量的優(yōu)惠碼的實例內(nèi)容以及相關(guān)代碼,有需要的朋友們學(xué)習(xí)下。2019-06-06