Python中iter函數(shù)的具體使用
因為在jax的代碼接觸了這個函數(shù),不是很熟悉,每次看見名字只知道是迭代但是不知道是怎么迭代,因此寫下以下筆記提醒自己。
def iter(source, sentinel=None): # known special case of iter """ iter(iterable) -> iterator iter(callable, sentinel) -> iterator Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel. """ pass
Python 中的 iter 函數(shù)
在 Python 編程中,iter
函數(shù)是一個非常有用的內置函數(shù),用于創(chuàng)建迭代器對象。迭代器是一種允許你遍歷集合(如列表、元組、字典等)中的元素的對象。iter
函數(shù)有兩種主要用法:
iter(iterable) -> iterator
:
這種形式接受一個可迭代對象(如列表、元組、字典等),并返回一個迭代器。迭代器可以用來遍歷可迭代對象的元素。
例如:
my_list = [1, 2, 3, 4, 5] iterator = iter(my_list) print(next(iterator)) # 輸出:1 print(next(iterator)) # 輸出:2
iter(callable, sentinel) -> iterator
:
這種形式接受一個可調用對象(如函數(shù))和一個哨兵值。它會調用可調用對象,直到返回哨兵值。
例如:
import random def my_callable(): return random.randint(1, 10) iterator = iter(my_callable, 5) print(next(iterator)) # 輸出:1 到 10 之間的隨機整數(shù) print(next(iterator)) # 輸出:1 到 10 之間的隨機整數(shù)
假設 my_callable 函數(shù)返回的隨機數(shù)序列是 [3, 7, 5, 2, 8],那么代碼的輸出可能是:
print(next(iterator)) # 輸出:3 print(next(iterator)) # 輸出:7
當 my_callable 函數(shù)返回 5 時,迭代器會停止,因為 5 是哨兵值。
自定義 iter 函數(shù)
為了更好地理解 iter
函數(shù)的工作原理,我們可以實現(xiàn)一個簡單的自定義版本:
def iter(source, sentinel=None): if sentinel is None: # Form 1: iter(iterable) return source.__iter__() else: # Form 2: iter(callable, sentinel) while True: value = source() if value == sentinel: break yield value
到此這篇關于Python中iter函數(shù)的具體使用的文章就介紹到這了,更多相關Python iter函數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python獲取接口數(shù)據(jù)的實現(xiàn)示例
本文主要介紹了Python獲取接口數(shù)據(jù)的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07Python 裝飾器@,對函數(shù)進行功能擴展操作示例【開閉原則】
這篇文章主要介紹了Python 裝飾器@,對函數(shù)進行功能擴展操作,結合實例形式分析了裝飾器的相關使用技巧,以及開閉原則下的函數(shù)功能擴展,需要的朋友可以參考下2019-10-10