<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Python 迭代器和生成器 > 原文: [http://zetcode.com/lang/python/itergener/](http://zetcode.com/lang/python/itergener/) 在 Python 教程的這一部分中,我們將使用插入器和生成器。 迭代器是一個對象,它使程序員可以遍歷集合的所有元素,而不管其具體實現如何。 在 Python 中,迭代器是實現迭代器協議的對象。 迭代器協議包含兩種方法。 `__iter__()`方法必須返回迭代器對象,而`next()`方法必須返回序列中的下一個元素。 迭代器具有以下優點: * 干凈的代碼 * 迭代器可以處理無限序列 * 迭代器節省資源 Python 有幾個內置對象,它們實現了迭代器協議。 例如列表,元組,字符串,字典或文件。 `iterator.py` ```py #!/usr/bin/env python # iterator.py str = "formidable" for e in str: print(e, end=" ") print() it = iter(str) print(it.next()) print(it.next()) print(it.next()) print(list(it)) ``` 在代碼示例中,我們顯示了字符串上的內置迭代器。 在 Python 中,字符串是不可變的字符序列。 `iter()`函數返回對象的迭代器。 我們還可以在迭代器上使用`list()`或`tuple()`函數。 ```py $ ./iterator.py f o r m i d a b l e f o r ['m', 'i', 'd', 'a', 'b', 'l', 'e'] ``` ## Python 閱讀一行 通過節省系統資源,我們的意思是在使用迭代器時,我們可以獲取序列中的下一個元素,而無需將整個數據集保留在內存中。 `read_data.py` ```py #!/usr/bin/env python # read_data.py with open('data.txt', 'r') as f: while True: line = f.readline() if not line: break else: print(line.rstrip()) ``` 此代碼打印`data.txt`文件的內容。 除了使用`while`循環外,我們還可以應用迭代器來簡化我們的任務。 `read_data_iterator.py` ```py #!/usr/bin/env python # read_data_iterator.py with open('data.txt', 'r') as f: for line in f: print(line.rstrip()) ``` `open()`函數返回一個文件對象,它是一個迭代器。 我們可以在`for`循環中使用它。 通過使用迭代器,代碼更清晰。 ## Python 迭代器協議 在下面的示例中,我們創建一個實現迭代器協議的自定義對象。 `iterator_protocol.py` ```py #!/usr/bin/env python # iterator_protocol.py class Seq: def __init__(self): self.x = 0 def __next__(self): self.x += 1 return self.x**self.x def __iter__(self): return self s = Seq() n = 0 for e in s: print(e) n += 1 if n > 10: break ``` 在代碼示例中,我們創建了一個數字序列 1,4,27,256,...。 這表明使用迭代器,我們可以處理無限序列。 ```py def __iter__(self): return self ``` `for`語句在容器對象上調用`__iter__()`函數。 該函數返回一個定義方法`__next__()`的迭代器對象,該方法一次訪問一個容器中的元素。 ```py def next(self): self.x += 1 return self.x**self.x ``` `next()`方法返回序列的下一個元素。 ```py if n > 10: break ``` 因為我們正在處理無限序列,所以我們必須中斷`for`循環。 ```py $ ./iterator.py 1 4 27 256 3125 46656 823543 16777216 387420489 10000000000 285311670611 ``` ## StopIteration 循環可以以其他方式中斷。 在類定義中,我們必須引發一個`StopIteration`異常。 在以下示例中,我們重做上一個示例。 `stopiter.py` ```py #!/usr/bin/env python # stopiter.py class Seq14: def __init__(self): self.x = 0 def __next__(self): self.x += 1 if self.x > 14: raise StopIteration return self.x ** self.x def __iter__(self): return self s = Seq14() for e in s: print(e) ``` 該代碼示例將打印序列的前 14 個數字。 ```py if self.x > 14: raise StopIteration ``` `StopIteration`異常將停止`for`循環。 ```py $ ./stop_iter.py 1 4 27 256 3125 46656 823543 16777216 387420489 10000000000 285311670611 8916100448256 302875106592253 11112006825558016 ``` 這是示例的輸出。 ## Python 生成器 生成器是一個特殊的例程,可用于控制循環的迭代行為。 生成器類似于返回數組的函數。 生成器具有參數,可以調用它并生成數字序列。 但是,與返回整個數組的函數不同,生成器一次生成一個值。 這需要較少的內存。 Python 中的生成器: * 用`def`關鍵字定義 * 使用`yield`關鍵字 * 可以使用幾個`yield`關鍵字 * 返回一個迭代器 讓我們看一個生成器示例。 `simple_generator.py` ```py #!/usr/bin/env python # simple_generator.py def gen(): x, y = 1, 2 yield x, y x += 1 yield x, y g = gen() print(next(g)) print(next(g)) try: print(next(g)) except StopIteration: print("Iteration finished") ``` 該程序將創建一個非常簡單的生成器。 ```py def gen(): x, y = 1, 2 yield x, y x += 1 yield x, y ``` 就像正常函數一樣,生成器使用`def`關鍵字定義。 我們在生成器主體內使用兩個`yield`關鍵字。 `yield`關鍵字退出生成器并返回一個值。 下次調用迭代器的`next()`函數時,我們在`yield`關鍵字之后的行繼續。 請注意,局部變量會在整個迭代過程中保留。 當沒有余量可產生時,將引發`StopIteration`異常。 ```py $ ./generator.py (1, 2) (2, 2) Iteration finished ``` 在以下示例中,我們計算斐波納契數。 序列的第一個數字為 0,第二個數字為 1,并且每個后續數字等于序列本身前兩個數字的和。 `fibonacci_gen.py` ```py #!/usr/bin/env python # fibonacci_gen.py import time def fib(): a, b = 0, 1 while True: yield b a, b = b, a + b g = fib() try: for e in g: print(e) time.sleep(1) except KeyboardInterrupt: print("Calculation stopped") ``` 該腳本將 Fibonacci 數字連續打印到控制臺。 用 `Ctrl + C` 組合鍵終止。 ## Python 生成器表達式 生成器表達式類似于列表推導。 區別在于生成器表達式返回的是生成器,而不是列表。 `generator_expression.py` ```py #!/usr/bin/env python # generator_expression.py n = (e for e in range(50000000) if not e % 3) i = 0 for e in n: print(e) i += 1 if i > 100: raise StopIteration ``` 該示例計算的值可以除以 3,而沒有余數。 ```py n = (e for e in range(50000000) if not e % 3) ``` 將使用圓括號創建生成器表達式。 在這種情況下,創建列表推導式將非常低效,因為該示例將不必要地占用大量內存。 為此,我們創建了一個生成器表達式,該表達式根據需要延遲生成值。 ```py i = 0 for e in n: print(e) i += 1 if i > 100: raise StopIteration ``` 在`for`循環中,我們使用生成器生成 100 個值。 我們這樣做時并沒有大量使用內存。 在下一個示例中,我們使用生成器表達式在 Python 中創建類似`grep`的工具。 `roman_empire.txt` ```py The Roman Empire (Latin: Imperium Rōmānum; Classical Latin: [?m?p?.ri.?? ro??ma?.n??] Koine and Medieval Greek: Βασιλε?α τ?ν ?ωμα?ων, tr. Basileia tōn Rhōmaiōn) was the post-Roman Republic period of the ancient Roman civilization, characterized by government headed by emperors and large territorial holdings around the Mediterranean Sea in Europe, Africa and Asia. The city of Rome was the largest city in the world c.?100 BC – c.?AD 400, with Constantinople (New Rome) becoming the largest around AD 500,[5][6] and the Empire's populace grew to an estimated 50 to 90 million inhabitants (roughly 20% of the world's population at the time).[n 7][7] The 500-year-old republic which preceded it was severely destabilized in a series of civil wars and political conflict, during which Julius Caesar was appointed as perpetual dictator and then assassinated in 44 BC. Civil wars and executions continued, culminating in the victory of Octavian, Caesar's adopted son, over Mark Antony and Cleopatra at the Battle of Actium in 31 BC and the annexation of Egypt. Octavian's power was then unassailable and in 27 BC the Roman Senate formally granted him overarching power and the new title Augustus, effectively marking the end of the Roman Republic. ``` 我們使用此文本文件。 `generator_expression.py` ```py #!/usr/bin/env python # gen_grep.py import sys def grep(pattern, lines): return ((line, lines.index(line)+1) for line in lines if pattern in line) file_name = sys.argv[2] pattern = sys.argv[1] with open(file_name, 'r') as f: lines = f.readlines() for line, n in grep(pattern, lines): print(n, line.rstrip()) ``` 該示例從文件中讀取數據,并打印包含指定模式及其行號的行。 ```py def grep(pattern, lines): return ((line, lines.index(line)+1) for line in lines if pattern in line) ``` 類似于`grep`的工具使用此生成器表達式。 該表達式遍歷行列表并選擇包含模式的行。 它計算列表中該行的索引,即它在文件中的行號。 ```py with open(file_name, 'r') as f: lines = f.readlines() for line, n in grep(pattern, lines): print(n, line.rstrip()) ``` 我們打開文件進行讀取,然后對數據調用`grep()`函數。 該函數返回一個生成器,該生成器通過`for`循環遍歷。 ```py $ ./gen_grep.py Roman roman_empire.txt 1 The Roman Empire (Latin: Imperium Rōmānum; Classical Latin: [?m?p?.ri.?? ro??ma?.n??] 3 post-Roman Republic period of the ancient Roman civilization, characterized by government 13 then unassailable and in 27 BC the Roman Senate formally granted him overarching power and 14 the new title Augustus, effectively marking the end of the Roman Republic. ``` 文件中有四行包含`Roman`字。 在本章中,我們介紹了 Python 中的迭代器和生成器。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看