国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

對python中的高效迭代器函數詳解

2020-01-04 14:19:03
字體:
來源:轉載
供稿:網友

python中內置的庫中有個itertools,可以滿足我們在編程中絕大多數需要迭代的場合,當然也可以自己造輪子,但是有現成的好用的輪子不妨也學習一下,看哪個用的順手~

首先還是要先import一下:

#import itertoolsfrom itertools import * #最好使用時用上面那個,不過下面的是為了演示比較  常用的,所以就直接全部導入了

一.無限迭代器:

python,高效迭代器,函數

由于這些都是無限迭代器,因此使用的時候都要設置終止條件,不然會一直運行下去,也就不是我們想要的結果了。

1、count()

可以設置兩個參數,第一個參數為起始點,且包含在內,第二個參數為步長,如果不設置第二個參數則默認步長為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()

可以設置一個參數,且只接受可以迭代的參數,如列表,元組,字符串。。。,該函數會對可迭代的所有元素進行循環:

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()

可以設置兩個參數,其中第一個參數要求可迭代,第二個參數為重復次數,第二個參數如不設置則無限循環,一般來說使用時都會設置第二個參數,用來滿足預期重復次數后終止:

#注意如果不設置第二個參數notebook運行可能會宕機for x in repeat(['a','b','c'],10): print x

二.有限迭代器

python,高效迭代器,函數

1、chain()

可以接受不定個數個可迭代參數,不要求可迭代參數類型相同,會返回一個列表,這個類似于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()

第一個參數為可迭代類型,第二個參數為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()

接受兩個參數,第一個參數為一個判斷類似于if語句的函數,丟棄滿足的項,直到第一個不滿足的項出現時停止丟棄,就是

#偽代碼大概是這個樣子的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

對給定可迭代集合(有重復元素)進行分組,返回的是一個元組,元組的第一個為分組的元素,第二個為分組的元素集合,還是看代碼吧:

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函數了,不過有點不同,filter返回的是一個完成后的列表,而ifilter則是一個生成器,使用的yield

#這樣寫只是為了更清楚看到輸出,其實這么寫就跟filter用法一樣了,體現不到ifilter的優越之處了list(ifilter(lambda x:x%2,range(10)))

6.ifilterfalse()

這個跟ifilter用法很像,只是兩個是相反數的關系。

list(ifilterfalse(lambda x:x%2,range(10)))

7.islice()

接受三個參數,可迭代參數,起始切片點,結束切片點,最少給定兩個參數,當只有兩個參數為默認第二個參數為結束切片點:

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()

接受參數個數跟目標函數有關:

#接受兩個參數時list(imap(abs,range(-5,5)))#接受三個參數時list(imap(pow,range(-5,5),range(10)))#接受四個參數時list(imap(lambda x,y,z:x+y+z,range(10),range(10),range(10)))

9.starmap()

這個是imap的變異,即只接受兩個參數,目標函數會作用在第二個參數集合中、

in: list(starmap(pow,[(1,2),(2,3)]))out: [1, 8]

10.tee()

接受兩個參數,第一個參數為可迭代類型,第二個為int,如果第二個不指定則默認為2,即重復兩次,有點像是生成器repeat的生成器類型,

這個就有意思了,是雙重生成器輸出:

for x in list(tee('abcde',3)): print list(x)

11.takewhile()

這個有點跟dropwhile()很是想象,一個是丟棄,一個是拿取:

偽代碼為:

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'))

三、組合迭代器

python,高效迭代器,函數

1.product()

這個有點像是多次使用for循環,兩者可以替代。

list(product(range(10),range(10)))#本質上是這種的生成器模式L = []for x in range(10): for y in range(10): L.append((x,y))

2.permutations()

接受兩個參數,第二個參數不設置時輸出的沒看出來是什么鬼,

第二個參數用來控制生成的元組的元素個數,而輸出的元組中最后一個元素是打亂次序的,暫時也不知道可以用在哪

list(permutations(range(10),2))

3.combinations()

用來排列組合,抽樣不放回,第二個參數為參與排列組合的個數

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中的高效迭代器函數詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 赤城县| 康乐县| 府谷县| 綦江县| 丹棱县| 成武县| 富裕县| 万盛区| 中江县| 仙桃市| 黔西县| 临江市| 芮城县| 双柏县| 宿州市| 广汉市| 乌恰县| 虞城县| 乌海市| 平塘县| 木里| 呈贡县| 施秉县| 富裕县| 秦皇岛市| 双辽市| 岳池县| 年辖:市辖区| 泰宁县| 怀宁县| 富川| 大渡口区| 瑞安市| 乌恰县| 清水河县| 石林| 阿坝| 错那县| 罗山县| 嘉善县| 偏关县|