日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

Python 推导,内含,迭代器

發(fā)布時間:2023/12/4 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 推导,内含,迭代器 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Python語法–推導(dǎo)或內(nèi)含

  • list comprehension操作可以將一個序列類型的數(shù)據(jù)集推導(dǎo)出另一個序列類型的數(shù)據(jù)集:
  • 典型的情況:
  • for i in aiterator
  • 利用推導(dǎo)獲取一個平方數(shù)列表
  • square = [i * i for i in range(1, 11)]
    • 以上情況同如下循環(huán)
    for i in range(1, 11):square.append(i * i)
  • 字典推導(dǎo)語法如下格式:
  • {key_exp:value_exp for key_exp,value_exp in aiterator}
    • 具體案例如下:
    keys = ['name', 'age', 'weight'] values = ['jiamin', '28', '81'] infoMap = {k: v for k, v in zip(keys, values)}
    推導(dǎo)+邏輯處理
  • 使用if語句實現(xiàn)選擇處理遍歷的元素,如下語法規(guī)則:
  • for i in aiterator if ... {key_exp:value_exp for key_exp,value_exp in aiterator if ...}
    • 具體案例如下
    ##取偶數(shù) square_odd = [i * i for i in range(1, 11) if i * i % 2 == 0] ##只取年齡 infoMap_odd = {k: v for k, v in zip(keys, values) if k == 'age'} ##通過字典生成字典 dict_one = {'name': 'jiamin', 'age': '28', 'weight': '81'} dict_two = {k: v for k, v in dict_one.items() if k == 'name'}

    python中迭代器

    • 迭代器是Python中一個數(shù)據(jù)量對象的容器,當(dāng)使用時候每次都從其中取出一個,直到取完
    自定義迭代器
    • 只要定義一個實現(xiàn)迭代器協(xié)議的方法類即可,主要協(xié)議方法與入學(xué)兩個
    __iter__() ## 方法放回對象本身,他是for語句使用迭代器的要求 __next__() ## 方法返回容器中下一個元素或數(shù)據(jù),當(dāng)容器中數(shù)據(jù)用完,應(yīng)該引發(fā)StopIteration
    • 自定義迭代器代碼如下:
    ## 自定義代器遍歷 class MyIterator:def __init__(self, x=2, xmax=100):self.__mul, self.__x = x, xself.__xmax = xmaxdef __iter__(self):return selfdef __next__(self):if self.__x and self.__x != 1:self.__mul *= self.__xif self.__mul <= self.__xmax:return self.__mulelse:raise StopIterationelse:raise StopIteration if __name__ == '__main__':myiter = MyIterator()for i in myiter:print('自定義迭代器: ', i)
    內(nèi)置迭代器工具
    • Python中內(nèi)建了一個用于產(chǎn)生迭代器的函數(shù)iter(),另外一個標(biāo)準(zhǔn)庫的itertools模塊還有豐富的迭代器工具:
    • 內(nèi)置迭代器工具實例:
    ## 內(nèi)建迭代器遍歷 class Counter:def __init__(self, x=0):self.x = xcounter = Counter()def used_iter():counter.x += 2return counter.xfor i in iter(used_iter, 8):print("內(nèi)建迭代器遍歷: ", i)
    itertools模塊中常用工具函數(shù)
    import itertools## 迭代器工具類 ## 從1 開始,每此以3 為步迭代 def countTest():for i in itertools.count(1, 3):print(i)if i >= 10:break##無線循環(huán)迭代 def cycleTest():for i in itertools.cycle([1, 2, 3]):print(i)## 循環(huán)迭代 輸出: [2, 2, 2] def repeatTest():print(list(itertools.repeat(2, 3)))##chain(p,q,...)鏈接迭代,將p,q連接起來迭代輸出:[1, 2, 3, 4, 5, 6] def chainTest():print(list(itertools.chain([1, 2, 3], [4, 5, 6])))## compress(data,selectors) 根據(jù)selectors中的值選擇迭代data序列中的值 輸出: [1, 3] def compressTest():print(list(itertools.compress([1, 2, 3, 4], [1, None, True, False])))## dropwhile(pred,seq) 當(dāng)pred對序列元素處理結(jié)果為False時候開始迭代seq后所有的值 輸出:[1, 2, 10, 11] def dropwhileTest():print(list(itertools.dropwhile(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))## filterfalse(pred,seq) 當(dāng)pred處理為假的元素 輸出:[1, 2] def filterfalseTest():print(list(itertools.filterfalse(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))## takewhile 與dropwhile相反 當(dāng)pred對序列元素處理結(jié)果為True時候開始迭代seq后所有的值 輸出:[8, 9] def takewhileTest():print(list(itertools.takewhile(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))## tee(it, n) 將it重復(fù)n次進(jìn)行迭代 def teeTest():for its in itertools.tee([0, 1], 2):for it in its:print(it)## zip_longest(p,q,...) 按每個序列中對應(yīng)位置元素組合成新的元素進(jìn)行迭代 def zip_longestTest():for i in itertools.zip_longest([1, 2, 3, 8], [3, 4, 5, 76], (0, 2, 3, 4)):print(i)## product(p,q,...[,n]) 迭代排列中出現(xiàn)元素的全排列 def productTest():for i in itertools.product([1, 2, 3, 8], [3, 4, 5, 76]):print(i)## permutations(p, q) 求p迭代序列中q個元素的全排列 def permutationsTest():print(list(itertools.permutations([1, 2, 3, 4], 4)))print(list(itertools.permutations('ASBD', 4)))## combinations(p, r)迭代序列中r個元素的組合 def combinationsTest():print(list(itertools.combinations('abc', 2)))print(list(itertools.combinations([1, 2, 3], 2)))if __name__ == '__main__':combinationsTest()

    總結(jié)

    以上是生活随笔為你收集整理的Python 推导,内含,迭代器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。