簡體   English   中英

Python 中是否有內置迭代器?

[英]Are there builtin iterators in Python?

我們有內置的可迭代對象,例如列表、元組和字典等等。 我們還可以通過在類中實現__iter__方法來創建我們自己的可迭代對象。 我們也可以通過實現一個__iter__和一個__next__方法來實現迭代器對象,但是有沒有像內置迭代器那樣的內置迭代器?

以下builtin函數在 Python 3 中返回迭代器: enumerate()filter()iter() (當然)、 map()reversed()zip()

在 Python 中也有很多返回迭代器的原生 Python 方法,例如 checkout itertools模塊(提示在名稱中!)。

然而,迂腐地回答你的問題,不存在不builtins迭代器(我想不出一個很好的使用情況如此),但作為tobias_klist()和其他人不iterables要么和只返回即可。


測試迭代器(不是對象)是否存在於builtins函數中(感謝FHTMitchell ):

import builtins
import collections.abc

def isiteratorclass(obj):
    if not isinstance(obj, type):
        return False
    return issubclass(obj, collections.abc.Iterator)


[key for key, value in vars(builtins).items() if isiteratorclass(value)]
# --> ['enumerate', 'filter', 'map', 'reversed', 'zip']

例如,文件句柄實現迭代器協議:

f = open('file.txt')
next(f)
# first line
next(f)
# second line

此代碼列出了實現iter 的每個內置函數

import builtins

for item in dir(builtins):
    class_ = getattr(builtins, item)
    if type(class_) is type:
        if hasattr(class_, '__iter__'):
            print(item)

打印以下可迭代

bytearray
bytes
dict
enumerate
filter
frozenset
list
map
range
reversed
set
str
tuple
zip

迭代器是對象,而不是類。 迭代器也是從對象創建的。

在標准庫中使用迭代器不是很有用,因為迭代器會耗盡。 當您對它們調用 next() 足夠多次時,它們最終將不會返回任何內容。

你還說像“zip”這樣的東西是“本機方法”。 嚴格來說並非如此。 'zip' 是一個類(見上文),而 zip() 創建 zip 類的一個實例。

將術語“功能”和“方法”視為截然不同的概念也很有幫助。 如果您的函數是在模塊(.py 文件)中定義的,那么它被稱為函數。 如果它在類中定義,則稱為方法。

Python 有點令人困惑,因為像 int 和 str 和 type 這樣的東西實際上是類,但我們像內置函數一樣使用它們。

在 builtins 模塊中進行探索非常有趣。 做就是了:

import builtins
dir(builtins)

然后檢查你在那里找到的一些東西的類型,比如:

>>> type(dir)
<class 'builtin_function_or_method'>

>>> type(zip)
<class 'type'>

>>> type(int)
<class 'type'>

>>> type(chr)
<class 'builtin_function_or_method'>

>>> type(type)
<class 'type'>

去看看它們到底是什么。 僅通過此練習,您將更深入地了解 Python 的工作原理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM