1樓:
l=('Ass'
,'We'
,'Can'
)# type of l is tuplee=enumerate(l
)# type of e is enumerate objectforv
inenumerate(e
):# type of enumerate(e) is enumerate object
print(v
)# type of v is tuple可以使用v[0]、v[1]的原因是v是乙個tuple。換句話說,enumerate object的__next__返回的結果是tuple。
不可以使用e[0]的原因是e是enumerate object型別。
enumerate的實現大致相當於下面這樣。當然實際肯定不是這麼實現的。
class
enumerate
:def
__init__
(self
,iterable_item
):self
.iterable_item
=iterable_item
self
.item
=iter
(iterable_item
)self
.index=0
def__iter__
(self
):return
self
def__next__
(self
):try
:curr_index
=self
.index
self
.index+=1
return
(curr_index
,next
(self
.item
))except
StopIteration
:self
.item
=iter
(self
.iterable_item
)self
.index=0
raise
StopIteration()
2樓:Yorlereiyo
你列印的時候就說的很清楚了 e 是乙個 enumerate object .
他既不是 tuple 也不是 list, 他就是 enumerate object.
我們看 enumerate object 的定義.
class
enumerate
(object
):"""
enumerate(iterable[, start]) -> iterator for index, value of iterable
Return an enumerate object. iterable must be another object that supports
iteration. The enumerate object yields pairs containing a count (from
start, which defaults to zero) and a value yielded by the iterable argument.
enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), ...
"""def
next
(self
):# real signature unknown; restored from __doc__
""" x.next() -> the next value, or raise StopIteration """
pass
def__getattribute__
(self
,name
):# real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass
def__init__
(self
,iterable
,start=0
):# known special case of enumerate.__init__
""" x.__init__(...) initializes x; see help(type(x)) for signature """
pass
def__iter__
(self
):# real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass
@staticmethod
# known case of __new__
def__new__(S
,*more
):# real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
可以看到他有 __iter__ 和 next 所以他是乙個 iterator
你所說的 tuple 是 iterator 在 for 語句中自動呼叫 next 方法的返回值
Python中ASCII,Unicode,UTF 8,encode,decode這些有什麼關係?
NoOffense ASCII,UTF 8是常用的字元編碼型別,Unicode是字符集,它們跟具體某一門語言 比如Python 無關,是計算機通行的標準。字元編碼型別規定了位元組 bytes 和字元 character 是如何對應的。例如ASCII中,10進製65代字元 A UTF 8中,16進製制...
Python中實現 a and b or c in xx 這種邏輯最簡潔的方式是怎樣的?
意群 不用lambda的話,最簡單的是用all。In 1 a,b,c 1,10,5In 2 xs list range 1 6 In 6 all i inxs foriin a,b orcinxs Out 6 True ohmyfish 使用 Perl 6 中的class Junction 是很簡潔...
python中的beautifulsoup和xpath有什麼異同點?
我覺得不同主要有以下幾點 學習曲線 效能曲線 對新手友好度 全宇宙最好的文字標籤解析庫當然是bs了,可一遇到js還是表示很無奈,非要說x系列快點實在沒有必要哈哈哈 我怎麼覺得xpath比bs好用多了。並且也很靈活。特別新版本的lxml更強大 beautifulsoup 是 HTML 解析庫,XPat...