欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python迭代器模塊itertools常用的方法

 更新時間:2022年09月15日 15:04:37   作者:Python熱愛者  
這篇文章主要介紹了python迭代器模塊itertools常用的方法,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下

前言

itertools是python中內(nèi)置的一種高效的生成各種迭代器或者是類的模塊,這些函數(shù)的返回值為一個迭代器,經(jīng)常被用在for循環(huán)中,當(dāng)然,也可直接使用next()方法取值,今天就來說說itertools中的常用方法.

itertools按照迭代器的功能可分為三類:

  • 無限迭代器: 生成一個無限序列,比如自然數(shù)序列 1, 2, 3, 4, …
  • 有限迭代器: 接收一個或多個序列(sequence)作為參數(shù),進(jìn)行組合、分組和過濾等;
  • 組合迭代器: 序列的排列、組合,求序列的笛卡兒積等

1.無限迭代器

itertools.count(start=0, step=1)

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

  • start: 起始值,默認(rèn)為0
  • step: 步長,默認(rèn)為1
import itertools
a = itertools.count()
for x in a:
    if x > 5:
        break
    print(x)

輸出:

1
2
3
4
5
6

b = itertools.count(2,3)
for x in b:
    if x > 10:
        break
    print(x)

輸出:

2
5
8

itertools.cycle(iterable)

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

iterable: 可迭代對象,可以為一個列表、字符串、元組等

import itertools
a = ['a','b','c']
i = 0
for x in itertools.cycle(a):
    i = i +1
    if i > 5:
        break
    print(i,x)

輸出:

1,'a'
2,'b'
3,'c'
4,'a'
5,'b'

itertools.repeat(object[, times])

創(chuàng)建一個迭代器,重復(fù)生成object,times(如果已提供)指定重復(fù)計數(shù),如果未提供times,將無止盡返回該對象

  • object: 需要重復(fù)的對象,對象是個整體
  • times: 重復(fù)次數(shù)
import itertools
for x in itertools.repeat([1,2,3],3):
    print(x)

輸出:

[1,2,3]
[1,2,3]
[1,2,3]

2.有限迭代器

itertools.chain(iterable1, iterable2, …)

將多個迭代器作為參數(shù), 但只返回單個迭代器, 它產(chǎn)生所有參數(shù)迭代器的內(nèi)容, 就好像他們是來自于一個單一的序列
參數(shù)為多個可迭代對象,就好像被鏈條銜接起來了一樣

import itertools
for x in itertools.chain([1,2,3],'abc'):
    print(x)

輸出:

1
2
3
'a'
'b'
'c'

for x in itertools.chain([1,2,3],['a','b','c']):
    print(x)

輸出:

1
2
3
'a'
'b'
'c'

itertools.chain.from_iterable(iterable)

接收一個可迭代對象作為參數(shù),返回一個迭代器

from itertools import chain
a = [['first','second','thrid'],['a','b','c']]
b = [[1,2,3],[4,5,6]]
for x in range(len(a)):
    list(chain.from_iterable(zip(a[x],b[x])))

輸出:

['first', 1, 'second', 2, 'thrid', 3]
['a', 4, 'b', 5, 'c', 6]

itertools.compress(data, selectors)

#可用于對數(shù)據(jù)進(jìn)行篩選,當(dāng) selectors 的某個元素為 true 時,則保留 data 對應(yīng)位置的元素,否則去除
#data: 待篩選數(shù)據(jù)
#selectors: 當(dāng)為真時,保留data對應(yīng)位的數(shù)據(jù),為假或為空時則去除

from itertools import compress
for x in compress(['a','b','c','d'],[1,0,2]):
    print(x)

輸出:

'a'
'c'
# 2 也為真,'d'對應(yīng)值為空算假

itertools.dropwhile(predicate, iterable)

創(chuàng)建一個迭代器,只要函數(shù)predicate(item)為True,就丟棄iterable中的項,如果predicate返回False,就會生成iterable中的項和所有后續(xù)項,即第一個不滿足條件的項及它后面所有的項都返回

  • predicate: 函數(shù)
  • iterable: 可迭代對象
from itertools import dropwhile
list(dropwhile(lambda x: x < 5, [1, 3, 6, 2, 1]))

輸出:

[6,2,1]
#從6開始不符合x < 5 條件,所以6及6后面所有的項都需要返回

itertools.takewhile(predicate, iterable)

創(chuàng)建一個迭代器,如果predicate返回False,立即停止迭代

from itertools import takewhile
list(takewhile(lambda x: x < 5, [1, 3, 6, 2, 1]))

輸出:

[1,3]

itertools.ifilter(predicate, iterable)

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

  • predicate: 函數(shù)
  • iterable: 可迭代對象
from itertools import ifilter
list(ifilter(lambda x: x < 5, [1, 3, 6, 2, 1]))

輸出:

[1,3,2,1]

itertools.ifilterfalse(predicate, iterable)

創(chuàng)建一個迭代器,僅生成iterable中predicate(item)為False的項,如果predicate為None,將返回iterable中所有計算False的項,該函數(shù)正好跟ifilter相反

  • predicate: 函數(shù)
  • iterable: 可迭代對象
from itertools import ifilterfalse
list(ifilterfalse(lambda x: x < 5, [1, 3, 6, 2, 1]))

輸出:

[6]

itertools.groupby(iterable[, key])

返回一個產(chǎn)生按照key進(jìn)行分組后的值集合的迭代器

  • iterable:可迭代對象
  • key: 一個函數(shù),該函數(shù)的返回值做為分組的標(biāo)準(zhǔn)
from itertools import groupby
a = ['aa', 'ab', 'abc', 'bcd', 'abcde']
for i, k in groupby(a, len):
     print (i, list(k))

輸出:

2,['aa', 'ab']
3,['abc', 'bcd']
5,['abcde']

itertools.islice(iterable, stop)

iterable 是可迭代對象,start 是開始索引,默認(rèn)為0,stop 是結(jié)束索引,step 是步長,默認(rèn)為1,start 和 step 可選

from itertools import islice,count
list(islice([10, 6, 2, 8, 1, 3, 9], 5))

輸出:

[[10, 6, 2, 8, 1]

list(islice(count(), 3, 10 ,2))

輸出:

 [3,5,7,9]
 #這里的count()為文章第一個函數(shù),用來產(chǎn)生無限序列

itertools.imap(func, iter1, iter2, iter3, …)

imap(func, iter1, iter2, iter3, …)
返回一個迭代器, 它是調(diào)用了一個其值在輸入迭代器上的函數(shù), 返回結(jié)果. 它類似于內(nèi)置函數(shù) map() , 只是前者在任意輸入迭代器結(jié)束后就停止(而不是插入None值來補(bǔ)全所有的輸入)
注意: 該函數(shù)在python3.x中已不存在,可直接使用map

from itertools import imap
list(imap(pow, [2, 3, 10], [4, 2, 3]))

輸出:

[16, 9, 1000]
#pow函數(shù) 求指數(shù)

itertools.izip(*iterables)

用于將多個可迭代對象對應(yīng)位置的元素作為一個元組,將所有元組『組成』一個迭代器,并返回
注意: 該函數(shù)在python3.x中已不存在,可直接使用zip

from itertools import izip
for item in izip([1, 2, 3], ['a', 'b', 'c', 'd', 'e']):
    print(item)

輸出:

(1, 'a')
(2, 'b')
(3, 'c')

*itertools.izip_longest(iterables, [fillvalue=None])

izip_longest 跟 izip 類似,但迭代過程會持續(xù)到所有可迭代對象的元素都被迭代完

注意: 該函數(shù)在python3.x中已不存在

from itertools import izip_longest
for item in izip_longest([1, 2, 3], ['a', 'b', 'c', 'd', 'e'],fillvalue='-'):
    print(item)

輸出:

(1, 'a')
(2, 'b')
(3, 'c')
('-','d')
('-','e')

3.組合迭代器

*itertools.product(iterables[, repeat])

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

import itertools
a = (1, 2, 3)
b = ('A', 'B', 'C')
c = itertools.product(a,b)
for elem in c:
    print(elem)

輸出:

(1, 'A')
(1, 'B')
(1, 'C')
(2, 'A')
(2, 'B')
(2, 'C')
(3, 'A')
(3, 'B')
(3, 'C')

list(product((0,1), (0,1), (0,1)))

輸出:

[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

list(product('ABC', repeat=2))

輸出:

[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]

itertools.product的簡單使用:

from itertools import product  # 迭代器

# test script
for i j in product(range(10),range(10))
    
print(i,j)
# 同理等于兩個for循環(huán)嵌套,只是這種寫法遠(yuǎn)行速度遍歷會快一些,時間復(fù)雜度減小。
for x in range(10):
    for y in range(10):
    print(x,y)

itertools.permutations(iterable[, r])

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

from itertools import permutations
list(permutations('ABC', 2))

輸出:

[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]

itertools.combinations(iterable, r)

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

from itertools import combinations
list(combinations('ABC', 2))

輸出:

[('A', 'B'), ('A', 'C'), ('B', 'C')]

itertools.combinations_with_replacement(iterable, r)

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

from itertools import combinations_with_replacement
list(combinations_with_replacement('ABC', 2))

輸出:

[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]

到此這篇關(guān)于python迭代器模塊itertools常用的方法的文章就介紹到這了,更多相關(guān)python itertools 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Pycharm編輯器功能之代碼折疊效果的實現(xiàn)代碼

    Pycharm編輯器功能之代碼折疊效果的實現(xiàn)代碼

    這篇文章主要介紹了Pycharm編輯器功能之代碼折疊效果的實現(xiàn)代碼,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-10-10
  • 將Python項目打包成exe并附帶下載功能的操作流程

    將Python項目打包成exe并附帶下載功能的操作流程

    這篇文章主要為大家詳細(xì)介紹了將Python項目打包成exe并附帶下載功能的操作流程,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,感興趣的小伙伴可以了解下
    2023-12-12
  • python數(shù)字圖像處理之骨架提取與分水嶺算法

    python數(shù)字圖像處理之骨架提取與分水嶺算法

    這篇文章主要介紹了python數(shù)字圖像處理之骨架提取與分水嶺算法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-04-04
  • python字符串格式化方式解析

    python字符串格式化方式解析

    這篇文章主要介紹了python字符串格式化方式解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-10-10
  • Python??序列化反序列化和異常處理的問題小結(jié)

    Python??序列化反序列化和異常處理的問題小結(jié)

    這篇文章主要介紹了Python?序列化反序列化和異常處理,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-12-12
  • python數(shù)據(jù)寫入列表并導(dǎo)出折線圖

    python數(shù)據(jù)寫入列表并導(dǎo)出折線圖

    這篇文章主要介紹了python數(shù)據(jù)寫入列表并導(dǎo)出折線圖,文章以舉例展開對文章主題的介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-01-01
  • python 調(diào)用Google翻譯接口的方法

    python 調(diào)用Google翻譯接口的方法

    這篇文章主要介紹了python 調(diào)用Google翻譯接口的方法,幫助大家更好的理解和使用python處理url,感興趣的朋友可以了解下
    2020-12-12
  • 使Python代碼流暢無縫連接的鏈?zhǔn)秸{(diào)用技巧

    使Python代碼流暢無縫連接的鏈?zhǔn)秸{(diào)用技巧

    鏈?zhǔn)秸{(diào)用是一種編程風(fēng)格,它允許將多個方法調(diào)用連接在一起,形成一個連貫的操作鏈,在Python中,鏈?zhǔn)秸{(diào)用常常用于使代碼更簡潔、易讀,尤其在處理數(shù)據(jù)處理和函數(shù)式編程中應(yīng)用廣泛
    2024-01-01
  • 使用 Python 處理3萬多條數(shù)據(jù)只要幾秒鐘

    使用 Python 處理3萬多條數(shù)據(jù)只要幾秒鐘

    在工作中經(jīng)常遇到大量的數(shù)據(jù)需要整合、去重、按照特定格式導(dǎo)出等情況。這篇文章主要介紹了使用 Python 處理3萬多條數(shù)據(jù)只要幾秒鐘的相關(guān)知識,需要的朋友可以參考下
    2020-01-01
  • Python檢測一個對象是否為字符串類的方法

    Python檢測一個對象是否為字符串類的方法

    這篇文章主要介紹了Python檢測一個對象是否為字符串類的方法,即檢測是一個對象是否是字符串對象,本文還講解了一個有趣的判斷方法,需要的朋友可以參考下
    2015-05-05

最新評論