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

首頁 > 編程 > Python > 正文

Python 迭代器工具包【推薦】

2019-11-25 16:48:30
字體:
供稿:網(wǎng)友

  原文:https://git.io/pytips

  0x01 介紹了迭代器的概念,即定義了 __iter__() __next__() 方法的對象,或者通過 yield 簡化定義的“可迭代對象”,而在一些函數(shù)式編程語言(見 0x02 Python 中的函數(shù)式編程)中,類似的迭代器常被用于產(chǎn)生特定格式的列表(或序列),這時的迭代器更像是一種數(shù)據(jù)結(jié)構(gòu)而非函數(shù)(當(dāng)然在一些函數(shù)式編程語言中,這兩者并無本質(zhì)差異)。Python 借鑒了 APL, Haskell, and SML 中的某些迭代器的構(gòu)造方法,并在 itertools 中實現(xiàn)(該模塊是通過 C 實現(xiàn),源代碼:/Modules/itertoolsmodule.c)。

  itertools 模塊提供了如下三類迭代器構(gòu)建工具:

  無限迭代

  整合兩序列迭代

  組合生成器

  1. 無限迭代

  所謂無限(infinite)是指如果你通過 for...in... 的語法對其進(jìn)行迭代,將陷入無限循環(huán),包括:

  

count(start, [step])  cycle(p)  repeat(elem [,n])

  從名字大概可以猜出它們的用法,既然說是無限迭代,我們自然不會想要將其所有元素依次迭代取出,而通常是結(jié)合 map/zip 等方法,將其作為一個取之不盡的數(shù)據(jù)倉庫,與有限長度的可迭代對象進(jìn)行組合操作:

  

from itertools import cycle, count, repeatprint(count.__doc__)  count(start=0, step=1) --> count object  Return a count object whose .__next__() method returns consecutive values.  Equivalent to:  def count(firstval=0, step=1):  x = firstval  while 1:  yield x  x += step  counter = count()  print(next(counter))  print(next(counter))  print(list(map(lambda x, y: x+y, range(10), counter)))  odd_counter = map(lambda x: 'Odd#{}'.format(x), count(1, 2))  print(next(odd_counter))  print(next(odd_counter))  0  1  [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]  Odd#1  Odd#3  print(cycle.__doc__)  cycle(iterable) --> cycle object  Return elements from the iterable until it is exhausted.  Then repeat the sequence indefinitely.  cyc = cycle(range(5))  print(list(zip(range(6), cyc)))  print(next(cyc))  print(next(cyc))  [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 0)]  1  2  print(repeat.__doc__)  repeat(object [,times]) -> create an iterator which returns the object  for the specified number of times. If not specified, returns the object  endlessly.  print(list(repeat('Py', 3)))  rep = repeat('p')  print(list(zip(rep, 'y'*3)))  ['Py', 'Py', 'Py']  [('p', 'y'), ('p', 'y'), ('p', 'y')]

  2. 整合兩序列迭代

  所謂整合兩序列,是指以兩個有限序列為輸入,將其整合操作之后返回為一個迭代器,最為常見的 zip 函數(shù)就屬于這一類別,只不過 zip 是內(nèi)置函數(shù)。這一類別完整的方法包括:

 

 accumulate()  chain()/chain.from_iterable()  compress()  dropwhile()/filterfalse()/takewhile()  groupby()  islice()  starmap()  tee()  zip_longest()

  這里就不對所有的方法一一舉例說明了,如果想要知道某個方法的用法,基本通過 print(method.__doc__) 就可以了解,畢竟 itertools 模塊只是提供了一種快捷方式,并沒有隱含什么深奧的算法。這里只對下面幾個我覺得比較有趣的方法進(jìn)行舉例說明。

  

from itertools import cycle, compress, islice, takewhile, count  # 這三個方法(如果使用恰當(dāng))可以限定無限迭代  # print(compress.__doc__)  print(list(compress(cycle('PY'), [1, 0, 1, 0])))  # 像操作列表 l[start:stop:step] 一樣操作其它序列  # print(islice.__doc__)  print(list(islice(cycle('PY'), 0, 2)))  # 限制版的 filter  # print(takewhile.__doc__)  print(list(takewhile(lambda x: x < 5, count())))  ['P', 'P']  ['P', 'Y']  [0, 1, 2, 3, 4]  from itertools import groupby  from operator import itemgetter  print(groupby.__doc__)  for k, g in groupby('AABBC'):  print(k, list(g))  db = [dict(name='python', script=True),  dict(name='c', script=False),  dict(name='c++', script=False),  dict(name='ruby', script=True)]  keyfunc = itemgetter('script')  db2 = sorted(db, key=keyfunc) # sorted by `script'  for isScript, langs in groupby(db2, keyfunc):  print(', '.join(map(itemgetter('name'), langs)))  groupby(iterable[, keyfunc]) -> create an iterator which returns  (key, sub-iterator) grouped by each value of key(value).  A ['A', 'A']  B ['B', 'B']  C ['C']  c, c++  python, ruby  from itertools import zip_longest  # 內(nèi)置函數(shù) zip 以較短序列為基準(zhǔn)進(jìn)行合并,  # zip_longest 則以最長序列為基準(zhǔn),并提供補(bǔ)足參數(shù) fillvalue  # Python 2.7 中名為 izip_longest  print(list(zip_longest('ABCD', '123', fillvalue=0)))  [('A', '1'), ('B', '2'), ('C', '3'), ('D', 0)]

  3. 組合生成器

  關(guān)于生成器的排列組合: 

product(*iterables, repeat=1):兩輸入序列的笛卡爾乘積  permutations(iterable, r=None):對輸入序列的完全排列組合  combinations(iterable, r):有序版的排列組合  combinations_with_replacement(iterable, r):有序版的笛卡爾乘積  from itertools import product, permutations, combinations, combinations_with_replacement  print(list(product(range(2), range(2))))  print(list(product('AB', repeat=2)))  [(0, 0), (0, 1), (1, 0), (1, 1)]  [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]  print(list(combinations_with_replacement('AB', 2)))  [('A', 'A'), ('A', 'B'), ('B', 'B')]  # 賽馬問題:4匹馬前2名的排列組合(A^4_2)  print(list(permutations('ABCDE', 2)))  [('A', 'B'), ('A', 'C'), ('A', 'D'),  ('A', 'E'), ('B', 'A'), ('B', 'C'),  ('B', 'D'), ('B', 'E'), ('C', 'A'),  ('C', 'B'), ('C', 'D'), ('C', 'E'),  ('D', 'A'), ('D', 'B'), ('D', 'C'),  ('D', 'E'), ('E', 'A'), ('E', 'B'), ('E', 'C'), ('E', 'D')]  # 彩球問題:4種顏色的球任意抽出2個的顏色組合(C^4_2)  print(list(combinations('ABCD', 2)))  [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 浑源县| 柳河县| 乌鲁木齐市| 威远县| 离岛区| 阜康市| 延边| 东兰县| 尚义县| 新邵县| 牙克石市| 密云县| 丹巴县| 辛集市| 武宁县| 镇原县| 新巴尔虎左旗| 长子县| 黔东| 麟游县| 沙田区| 宜君县| 彝良县| 吉首市| 独山县| 元阳县| 旺苍县| 平泉县| 石首市| 辽阳市| 澄城县| 大城县| 南平市| 樟树市| 岑溪市| 民乐县| 西青区| 金秀| 广元市| 贡觉县| 宾阳县|