日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

itertools:用于處理可迭代對象的模塊

來源: 責編: 時間:2024-03-25 17:35:10 179觀看
導讀Python 有一個內置模塊 itertools,從名字可以看出它是專門用來處理可迭代對象的,那么它都支持哪些操作呢?一起來看一下吧。itertools.chain接收多個可迭代對象(或者迭代器)作為參數,返回一個迭代器。它會生成所有輸入迭代器

Python 有一個內置模塊 itertools,從名字可以看出它是專門用來處理可迭代對象的,那么它都支持哪些操作呢?一起來看一下吧。gFh28資訊網——每日最新資訊28at.com

itertools.chain

接收多個可迭代對象(或者迭代器)作為參數,返回一個迭代器。它會生成所有輸入迭代器的元素,就好像這些元素來自一個迭代器一樣。gFh28資訊網——每日最新資訊28at.com

import itertoolsc = itertools.chain([1, 2, 3], "abc", {"k1": "v1", "k2": "v2"})# 直接打印的話是一個對象print(c) """<itertools.chain object at 0x00000000029745F8>"""print(list(c)) """1 2 3 a b c k1 k2"""# 還可以使用 chain.from_iterable# 參數接收多個可迭代對象組成的一個可迭代對象c = itertools.chain.from_iterable(    [[1, 2, 3], "abc", {"k1": "v1", "k2": "v2"}])print(list(c)) """1 2 3 a b c k1 k2"""

gFh28資訊網——每日最新資訊28at.com

itertools.zip_longest

從名字上可以看出,功能和內置的 zip 類似。確實如此,就是將多個可迭代對象對應位置的元素組合起來,像拉鏈(zip)一樣。只不過內置的 zip 是 "木桶原理",一方匹配到頭了,那么就不匹配了,而 zip_longest 是以長的那一方為基準。gFh28資訊網——每日最新資訊28at.com

import itertools# 內置的 zip 是把多個迭代器對象中的每一個元素按照順序組合到一個元組中name = ["高老師", "豬哥", "S 佬"]where = ["江蘇", "北京", "深圳"]z = zip(name, where)print(z)"""<zip object at 0x00000257F3FEBEC0>"""print(list(z))"""[('高老師', '江蘇'), ('豬哥', '北京'), ('S 佬', '深圳')]"""# 但如果兩者長度不一致怎么辦?name = ["高老師", "豬哥", "S 佬", "xxx"]where = ["江蘇", "北京", "深圳"]print(list(zip(name, where)))"""[('高老師', '江蘇'), ('豬哥', '北京'), ('S 佬', '深圳')]"""# 可以看到,長度不一致的時候,當一方結束之后就停止匹配# 如果想匹配長的,那么可以使用 itertools 下面的 zip_longestprint(list(itertools.zip_longest(name, where))) """[('高老師', '江蘇'), ('豬哥', '北京'), ('S 佬', '深圳'), ('xxx', None)]"""# 默認使用 None 進行匹配,當然我們也可以指定內容print(list(itertools.zip_longest(name, where, fillvalue="中國")))"""[('高老師', '江蘇'), ('豬哥', '北京'), ('S 佬', '深圳'), ('xxx', '中國')]"""

gFh28資訊網——每日最新資訊28at.com

itertools.islice

如果一個迭代器里面包含了很多元素,我們只想要一部分的話,可以使用 islice,按照索引從迭代器中返回所選擇的元素,并且得到的還是一個迭代器。gFh28資訊網——每日最新資訊28at.com

import itertoolsnum = range(20)# 選擇 index=5 到 index=10(不包含)的位置s = itertools.islice(num, 5, 10)print(list(s))  # [5, 6, 7, 8, 9]# 選擇開頭到 index=5 的位置s = itertools.islice(num, 5)print(list(s))  # [0, 1, 2, 3, 4]# 選擇從 index=5 到 index=15(不包含)的位置,步長為 3s = itertools.islice(num, 5, 15, 3)print(list(s))  # [5, 8, 11, 14]

注意:islice 不支持負數索引,因為不知道迭代器有多長,除非全部讀取,可是那樣的話干嘛不直接轉為列表之后再用切片獲取呢?gFh28資訊網——每日最新資訊28at.com

之所以使用 islice 這種形式,就是為了在不全部讀取的情況下,也能選擇出我們想要的部分,所以這種方式只支持從前往后,不能從后往前。gFh28資訊網——每日最新資訊28at.com

itertools.tee

將一個可迭代對象拷貝 n 份。gFh28資訊網——每日最新資訊28at.com

import itertoolsr = [1, 2, 3, 4, 5]i1, i2 = itertools.tee(r, 2)print(list(i1))  # [1, 2, 3, 4, 5]print(list(i2))  # [1, 2, 3, 4, 5]

gFh28資訊網——每日最新資訊28at.com

itertools.countgFh28資訊網——每日最新資訊28at.com

import itertools"""count(start=0, step=1) 返回一個迭代器,負責無限地生成連續的整數接收兩個參數:起始(默認為0)和步長(默認為1)等價于:def count(firstval=0, step=1):    x = firstval    while 1:        yield x        x += step"""# 起始值為 5,步長為 2c1 = itertools.count(5, 2)print(list(itertools.islice(c1, 5))) """[5, 7, 9, 11, 13]"""

gFh28資訊網——每日最新資訊28at.com

itertools.cycle

import itertools"""cycle(iterable) 返回一個迭代器,會無限重復里面的內容,直到內存耗盡"""c2 = itertools.cycle("abc")print(list(itertools.islice(c2, 10)))"""['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']"""

gFh28資訊網——每日最新資訊28at.com

itertools.repeat

import itertools"""repeat(obj, times=None),無限重復 obj,除非指定 times"""# 重復指定的次數print(list(itertools.repeat("abc", 3))) """['abc', 'abc', 'abc']"""

gFh28資訊網——每日最新資訊28at.com

itertools.dropwhile

刪除滿足條件的值,注意:是刪除。gFh28資訊網——每日最新資訊28at.com

import itertoolsl = [1, 2, 3, 4, 5]drop_l = itertools.dropwhile(lambda x: x < 3, l)# 依舊返回迭代器print(drop_l) """<itertools.dropwhile object at 0x000001AD63AD0488>"""# 可以看到小于3的都被丟掉了print(list(drop_l))  """[3, 4, 5]"""

gFh28資訊網——每日最新資訊28at.com

itertools.takewhile

這個和 filter 是一樣的,保留滿足條件的值。gFh28資訊網——每日最新資訊28at.com

import itertoolsl = [1, 2, 3, 4, 5]take_l = itertools.takewhile(lambda x: x < 3, l)print(take_l) """<itertools.takewhile object at 0x000001D37F512948>"""print(list(take_l)) """[1, 2]"""filter_l = filter(lambda x: x < 3, l)print(list(filter_l))  """[1, 2]"""

gFh28資訊網——每日最新資訊28at.com

itertools.compress

提供了另一種過濾可迭代對象元素的方法。gFh28資訊網——每日最新資訊28at.com

import itertoolscondition = [True, False, True, True, False]data = [1, 2, 3, 4, 5]print(list(itertools.compress(data, condition))) """[1, 3, 4]"""# 除了指定 True 和 False,還可以使用 Python 其它類型的值# 會以其對應的布爾值作為判斷依據condition = [1, 0, "x", "x", {}]  print(list(itertools.compress(data, condition))) """[1, 3, 4]"""

gFh28資訊網——每日最新資訊28at.com

itertools.accumulategFh28資訊網——每日最新資訊28at.com

accumulate 處理輸入的序列,得到一個類似于斐波那契的結果。gFh28資訊網——每日最新資訊28at.com

import itertoolsprint(list(itertools.accumulate(range(5))))  """[0, 1, 3, 6, 10]"""print(list(itertools.accumulate("abcde")))  """["a", "ab", "abc", "abcd", "abcde"]"""# 所以這里的相加還要看具體的含義try:    print(list(itertools.accumulate([[1, 2], (3, 4)])))except TypeError as e:    print(e)      """    can only concatenate list (not "tuple") to list    """    # 這里就顯示無法將列表和元組相加# 當然也可以自定義data = [1, 2, 3, 4, 5]method = lambda x, y: x * yprint(list(itertools.accumulate(data, method))) """[1, 2, 6, 24, 120]"""# 可以看到這里的結果就改變了

gFh28資訊網——每日最新資訊28at.com

itertools.productgFh28資訊網——每日最新資訊28at.com

product 則是會將多個可迭代對象組合成一個笛卡爾積。gFh28資訊網——每日最新資訊28at.com

import itertoolsprint(list(itertools.product([1, 2, 3], [2, 3]))) """[(1, 2), (1, 3), (2, 2), (2, 3), (3, 2), (3, 3)]"""

gFh28資訊網——每日最新資訊28at.com

itertools.permutationsgFh28資訊網——每日最新資訊28at.com

import itertoolsdata = [1, 2, 3, 4]print(list(itertools.permutations(data)))# 根據排列組合,顯然是 A44,總共 4 * 3 * 2 * 1 = 24 種組合"""[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2),(2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1),(3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1),(4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]"""# 結果是 A42,總共 4 * 3 = 12 種組合print(list(itertools.permutations(data, 2)))"""[(1, 2), (1, 3), (1, 4),  (2, 1), (2, 3), (2, 4),  (3, 1), (3, 2), (3, 4),  (4, 1), (4, 2), (4, 3)]"""

gFh28資訊網——每日最新資訊28at.com

itertools.combinationsgFh28資訊網——每日最新資訊28at.com

permutations 顯然是考慮了順序,相當于排列組合里面 A,而 combinations 只考慮元素是否一致,而不管順序,相當于排列組合里面的 C。gFh28資訊網——每日最新資訊28at.com

import itertools# permutations 只要順序不同就看做一種結果# combinations 則保證只要元素相同就是同一種結果data = "abcd"print(list(itertools.combinations(data, 3)))  """[('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd')]"""# 如果拿抽小球來作比喻的話,顯然 combinations 是不放回的,也就是不會重復單個的輸入元素# 但有時候可能也需要考慮包含重復元素的組合,相當于抽小球的時候有放回# 對于這種情況,可以使用 combinations_with_replacementprint(list(itertools.combinations_with_replacement(data, 3)))"""[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'a', 'd'), ('a', 'b', 'b'),('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'c'), ('a', 'c', 'd'), ('a', 'd', 'd'),('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'b', 'd'), ('b', 'c', 'c'), ('b', 'c', 'd'),('b', 'd', 'd'), ('c', 'c', 'c'), ('c', 'c', 'd'), ('c', 'd', 'd'), ('d', 'd', 'd')]"""

gFh28資訊網——每日最新資訊28at.com

以上就是該模塊的用法,但說實話,感覺大部分都沒啥卵用。gFh28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-79141-0.htmlitertools:用于處理可迭代對象的模塊

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 快速了解CSS表單尺寸屬性field-sizing

下一篇: Spring Boot郵件發送教程:步步為營,輕松實現圖片附件郵件!

標簽:
  • 熱門焦點
Top 主站蜘蛛池模板: 蓬莱市| 上饶市| 育儿| 奉贤区| 内江市| 崇阳县| 登封市| 韶关市| 云霄县| 华安县| 谷城县| 澳门| 宜兰市| 武穴市| 鄄城县| 汉川市| 库车县| 泰和县| 依安县| 嘉祥县| 滁州市| 台南市| 兴国县| 连南| 通河县| 通州市| 盐源县| 离岛区| 正镶白旗| 朝阳区| 长宁区| 修水县| 房产| 光泽县| 彭阳县| 乳源| 浏阳市| 基隆市| 福贡县| 白山市| 中牟县|