1 回答

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
您對(duì)其最終作用的理解是正確的,但該引文中的措辭具有誤導(dǎo)性?!懊杜e器”(不是真正的標(biāo)準(zhǔn)術(shù)語(yǔ))和迭代器之間沒(méi)有區(qū)別,或者更確切地說(shuō),“枚舉器”是一種迭代器。enumerate返回一個(gè)enumerate對(duì)象,類enumerate也是:
>>> enumerate
<class 'enumerate'>
>>> type(enumerate)
<class 'type'>
>>> enumerate(())
<enumerate object at 0x10ad9c300>
就像其他內(nèi)置類型一樣list:
>>> list
<class 'list'>
>>> type(list)
<class 'type'>
>>> type([1,2,3]) is list
True
或自定義類型:
>>> class Foo:
... pass
...
>>> Foo
<class '__main__.Foo'>
<class 'type'>
>>> type(Foo())
<class '__main__.Foo'>
>>>
enumerate對(duì)象是迭代器。并不是說(shuō)它們可以被“視為”迭代器,它們是迭代器,迭代器是滿足以下條件的任何類型:它們定義了 a__iter__和__next__:
>>> en = enumerate([1])
>>> en.__iter__
<method-wrapper '__iter__' of enumerate object at 0x10ad9c440>
>>> en.__next__
<method-wrapper '__next__' of enumerate object at 0x10ad9c440>
并且iter(iterator) is iterator:
>>> iter(en) is en
True
>>> en
<enumerate object at 0x10ad9c440>
>>> iter(en)
<enumerate object at 0x10ad9c440>
看:
>>> next(en)
(0, 1)
現(xiàn)在,具體來(lái)說(shuō),它本身并不返回索引值,而是返回一個(gè)二元組,其中包含傳入的迭代中的下一個(gè)值以及單調(diào)遞增的整數(shù),默認(rèn)情況下從 開(kāi)始0,但它可以采用start參數(shù),并且傳入的迭代不必是可索引的:
>>> class Iterable:
... def __iter__(self):
... yield 1
... yield 2
... yield 3
...
>>> iterable = Iterable()
>>> iterable[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Iterable' object is not subscriptable
>>> list(enumerate(iterable))
[(0, 1), (1, 2), (2, 3)]
>>> list(enumerate(iterable, start=1))
[(1, 1), (2, 2), (3, 3)]
>>> list(enumerate(iterable, start=17))
[(17, 1), (18, 2), (19, 3)]
添加回答
舉報(bào)