欧美三区_成人在线免费观看视频_欧美极品少妇xxxxⅹ免费视频_a级毛片免费播放_鲁一鲁中文字幕久久_亚洲一级特黄

Python中itertools模塊用法詳解

系統(tǒng) 1753 0

本文實例講述了Python中itertools模塊用法,分享給大家供大家參考。具體分析如下:

一般來說,itertools模塊包含創(chuàng)建有效迭代器的函數(shù),可以用各種方式對數(shù)據(jù)進行循環(huán)操作,此模塊中的所有函數(shù)返回的迭代器都可以與for循環(huán)語句以及其他包含迭代器(如生成器和生成器表達式)的函數(shù)聯(lián)合使用。

chain(iter1, iter2, ..., iterN):

給出一組迭代器(iter1, iter2, ..., iterN),此函數(shù)創(chuàng)建一個新迭代器來將所有的迭代器鏈接起來,返回的迭代器從iter1開始生成項,知道iter1被用完,然后從iter2生成項,這一過程會持續(xù)到iterN中所有的項都被用完。

            
from itertools import chain
test = chain('AB', 'CDE', 'F')
for el in test:
  print el

A
B
C
D
E
F


          

chain.from_iterable(iterables):

一個備用鏈構(gòu)造函數(shù),其中的iterables是一個迭代變量,生成迭代序列,此操作的結(jié)果與以下生成器代碼片段生成的結(jié)果相同:

            
>>> def f(iterables):
  for x in iterables:
    for y in x:
      yield y

>>> test = f('ABCDEF')
>>> test.next()
'A'


>>> from itertools import chain
>>> test = chain.from_iterable('ABCDEF')
>>> test.next()
'A'


          

combinations(iterable, r):

創(chuàng)建一個迭代器,返回iterable中所有長度為r的子序列,返回的子序列中的項按輸入iterable中的順序排序:

            
>>> from itertools import combinations
>>> test = combinations([1,2,3,4], 2)
>>> for el in test:
  print el

  
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)


          

count([n]):

創(chuàng)建一個迭代器,生成從n開始的連續(xù)整數(shù),如果忽略n,則從0開始計算(注意:此迭代器不支持長整數(shù)),如果超出了sys.maxint,計數(shù)器將溢出并繼續(xù)從-sys.maxint-1開始計算。

cycle(iterable):

創(chuàng)建一個迭代器,對iterable中的元素反復(fù)執(zhí)行循環(huán)操作,內(nèi)部會生成iterable中的元素的一個副本,此副本用于返回循環(huán)中的重復(fù)項。

dropwhile(predicate, iterable):

創(chuàng)建一個迭代器,只要函數(shù)predicate(item)為True,就丟棄iterable中的項,如果predicate返回False,就會生成iterable中的項和所有后續(xù)項。

            
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


          

groupby(iterable [,key]):

創(chuàng)建一個迭代器,對iterable生成的連續(xù)項進行分組,在分組過程中會查找重復(fù)項。

如果iterable在多次連續(xù)迭代中生成了同一項,則會定義一個組,如果將此函數(shù)應(yīng)用一個分類列表,那么分組將定義該列表中的所有唯一項,key(如果已提供)是一個函數(shù),應(yīng)用于每一項,如果此函數(shù)存在返回值,該值將用于后續(xù)項而不是該項本身進行比較,此函數(shù)返回的迭代器生成元素(key, group),其中key是分組的鍵值,group是迭代器,生成組成該組的所有項。

ifilter(predicate, iterable):
創(chuàng)建一個迭代器,僅生成iterable中predicate(item)為True的項,如果predicate為None,將返回iterable中所有計算為True的項。

            
ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9

          

?
ifilterfalse(predicate, iterable):
創(chuàng)建一個迭代器,僅生成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)
創(chuàng)建一個迭代器,生成項function(i1, i2, ..., iN),其中i1,i2...iN分別來自迭代器iter1,iter2 ... iterN,如果function為None,則返回(i1, i2, ..., iN)形式的元組,只要提供的一個迭代器不再生成值,迭代就會停止。

            
>>> from itertools import *
 >>> d = imap(pow, (2,3,10), (5,2,3))
 >>> for i in d: print i
 
 32
 9
 1000
 
 ####
 >>> d = imap(pow, (2,3,10), (5,2))
 >>> for i in d: print i
 
 32
 9

 ####
 >>> d = imap(None, (2,3,10), (5,2))
 >>> for i in d : print i
 
 (2, 5)
 (3, 2)


          

islice(iterable, [start, ] stop [, step]):
創(chuàng)建一個迭代器,生成項的方式類似于切片返回值: iterable[start : stop : step],將跳過前start個項,迭代在stop所指定的位置停止,step指定用于跳過項的步幅。與切片不同,負值不會用于任何start,stop和step,如果省略了start,迭代將從0開始,如果省略了step,步幅將采用1.

            
def islice(iterable, *args):
   # 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.
#Changed in version 2.5: accept None values for default start and step.


          

izip(iter1, iter2, ... iterN):
創(chuàng)建一個迭代器,生成元組(i1, i2, ... iN),其中i1,i2 ... iN 分別來自迭代器iter1,iter2 ... iterN,只要提供的某個迭代器不再生成值,迭代就會停止,此函數(shù)生成的值與內(nèi)置的zip()函數(shù)相同。

            
def izip(*iterables):
   # izip('ABCD', 'xy') --> Ax By
   iterables = map(iter, iterables)
   while iterables:
     yield tuple(map(next, iterables))


          

izip_longest(iter1, iter2, ... iterN, [fillvalue=None]):
與izip()相同,但是迭代過程會持續(xù)到所有輸入迭代變量iter1,iter2等都耗盡為止,如果沒有使用fillvalue關(guān)鍵字參數(shù)指定不同的值,則使用None來填充已經(jīng)使用的迭代變量的值。

            
def izip_longest(*args, **kwds):
   # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
   fillvalue = kwds.get('fillvalue')
   def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
     yield counter()     # yields the fillvalue, or raises IndexError
   fillers = repeat(fillvalue)
   iters = [chain(it, sentinel(), fillers) for it in args]
   try:
     for tup in izip(*iters):
       yield tup
   except IndexError:
     pass


          

permutations(iterable [,r]):

創(chuàng)建一個迭代器,返回iterable中所有長度為r的項目序列,如果省略了r,那么序列的長度與iterable中的項目數(shù)量相同:

            
def permutations(iterable, r=None):
   # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
   # permutations(range(3)) --> 012 021 102 120 201 210
   pool = tuple(iterable)
   n = len(pool)
   r = n if r is None else r
   if r > n:
     return
   indices = range(n)
   cycles = range(n, n-r, -1)
   yield tuple(pool[i] for i in indices[:r])
   while n:
     for i in reversed(range(r)):
       cycles[i] -= 1
       if cycles[i] == 0:
         indices[i:] = indices[i+1:] + indices[i:i+1]
         cycles[i] = n - i
       else:
         j = cycles[i]
         indices[i], indices[-j] = indices[-j], indices[i]
         yield tuple(pool[i] for i in indices[:r])
         break
     else:
       return


          

product(iter1, iter2, ... iterN, [repeat=1]):

創(chuàng)建一個迭代器,生成表示item1,item2等中的項目的笛卡爾積的元組,repeat是一個關(guān)鍵字參數(shù),指定重復(fù)生成序列的次數(shù)。

            
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)


          

repeat(object [,times]):
創(chuàng)建一個迭代器,重復(fù)生成object,times(如果已提供)指定重復(fù)計數(shù),如果未提供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(times):
       yield object


          

starmap(func [, iterable]):
創(chuàng)建一個迭代器,生成值func(*item),其中item來自iterable,只有當(dāng)iterable生成的項適用于這種調(diào)用函數(shù)的方式時,此函數(shù)才有效。

            
def starmap(function, iterable):
   # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
   for args in iterable:
     yield function(*args)


          

takewhile(predicate [, iterable]):
創(chuàng)建一個迭代器,生成iterable中predicate(item)為True的項,只要predicate計算為False,迭代就會立即停止。

            
def takewhile(predicate, iterable):
   # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
   for x in iterable:
     if predicate(x):
       yield x
     else:
       break


          

tee(iterable [, n]):
從iterable創(chuàng)建n個獨立的迭代器,創(chuàng)建的迭代器以n元組的形式返回,n的默認值為2,此函數(shù)適用于任何可迭代的對象,但是,為了克隆原始迭代器,生成的項會被緩存,并在所有新創(chuàng)建的迭代器中使用,一定要注意,不要在調(diào)用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().


          

相信本文所述對大家Python程序設(shè)計的學(xué)習(xí)有一定的借鑒價值。


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 国产精品毛片久久久久久 | 国产精品国产午夜免费福利看 | 夜色成人网 | aaa毛片免费观看 | 99在线精品视频免费观里 | 国产精品一区久久久 | 久久激情av| 色狠狠色狠狠综合一区 | 天干天夜啪天天碰 | 国产精品1区2区3区 亚洲国产aⅴ成人精品无吗 | 草草影院地址 | 成人免费一区二区三区视频软件 | 亚洲经典激情春色另类 | 在线看av网址 | 国产精品久久人妻无码网站一区无 | 91看大片 | 国产成人综合一区精品 | 免费黄色欧美视频 | 两女互慰磨豆腐视频在线观看 | 久久国产婷婷国产香蕉 | 久久久国产一区二区三区 | 午夜激情视频在线观看 | 国产精品入口免费麻豆 | 色屁屁www免费看视频影院 | 12306播播影院午夜 | 99动漫| 免费成人高清在线视频 | 99热这里有免费国产精品 | 男生插女生视频免费 | 一级aaaaaa片毛片在线播放 | 亚洲欧洲日本在线 | 久操国产视频 | 男人的天堂在线视频 | 99精品在线免费观看 | 日韩在线视频观看 | 日本瑟瑟 | 国产亚洲欧美日韩v在线 | 天天摸夜夜摸狠狠摸夜夜摸 | 日韩中文字幕av | 亚欧视频在线观看 | 国产精品99久久 |