一、迭代器
1.1 判斷一個對象是否可迭代
In [50]:
from
collections
import
Iterable
In [
51
]: isinstance([], Iterable)
Out[
51
]: True
In [
52
]: isinstance({}, Iterable)
Out[
52
]: True
In [
53]: isinstance(
'
abc
'
, Iterable)
Out[
53
]: True
In [
54
]: isinstance(mylist, Iterable)
Out[
54
]: False
In [
55]: isinstance(100
, Iterable)
Out[
55]: False
1.2 可迭代對象的本質
1
from
collections
import
Iterable
2
3
4
class
MyList(object):
5
6
def
__init__
(self):
7
self.container =
[]
8
9
def
add(self, item):
10
self.container.append(item)
11
12
def
__iter__
(self):
13
"""
返回一個迭代器
"""
14
pass
15
16
17
mylist =
MyList()
18
print
(isinstance(mylist, Iterable))
#
True
這回測試發現添加了__iter__方法的mylist對象已經是一個可迭代對象了
1.3 iter()函數和next()函數
>>> li = [11, 22, 33, 44, 55
]
>>> li_iter =
iter(li)
>>>
next(li_iter)
11
>>>
next(li_iter)
22
>>>
next(li_iter)
33
>>>
next(li_iter)
44
>>>
next(li_iter)
55
>>>
next(li_iter)
Traceback (most recent call last):
File
"
"
, line 1,
in
StopIteration
>>>
注意,當我們已經迭代完最后一個數據之后,再次調用next()函數會拋出StopIteration的異常,來告訴我們所有數據都已迭代完成,不用再執行next()函數了。
1.4?如何判斷一個對象是否是迭代器
可以使用 isinstance() 判斷一個對象是否是 Iterator 對象:
In [56]:
from
collections
import
Iterator
In [
57
]: isinstance([], Iterator)
Out[
57
]: False
In [
58
]: isinstance(iter([]), Iterator)
Out[
58
]: True
In [
59]: isinstance(iter(
"
abc
"
), Iterator)
Out[
59]: True
1.5 迭代器Iterator
1
#
實現迭代器(兩個類的寫法)
2
class
MyList(object):
3
"""
4
自定義的一個可迭代對象
5
"""
6
7
def
__init__
(self):
8
self.items =
[]
9
10
def
add(self, val):
11
self.items.append(val)
12
13
def
__iter__
(self):
14
myiterator =
MyIterator(self)
15
16
return
myiterator
17
18
19
class
MyIterator(object):
20
"""
21
自定義的供上面可迭代對象使用的一個迭代器
22
"""
23
def
__init__
(self, mylist):
24
self.mylist =
mylist
25
#
current用來記錄當前訪問到的位置
26
self.current =
0
27
28
def
__next__
(self):
29
if
self.current <
len(self.mylist.items):
30
item =
self.mylist.items[self.current]
31
self.current += 1
32
return
item
33
else
:
34
raise
StopIteration
35
36
def
__iter__
(self):
37
return
self
38
39
40
if
__name__
==
'
__main__
'
:
41
mylist =
MyList()
42
mylist.add(1
)
43
mylist.add(2
)
44
mylist.add(3
)
45
mylist.add(4
)
46
mylist.add(5
)
47
for
num
in
mylist:
48
print
(num)
1
實現迭代器(寫在一個類)
2
class
MyList(object):
3
4
5
def
__init__
(self):
6
self.container =
[]
7
self.current =
0
8
9
10
def
add(self, item):
11
self.container.append(item)
12
13
14
def
__iter__
(self):
15
16
17
return
self
18
19
20
def
__next__
(self):
21
if
self.current <
len(self.container):
22
item =
self.container[self.current]
23
self.current += 1
24
return
item
25
else
:
26
raise
StopIteration
27
28
29
30
31
my_list =
MyList()
32
my_list.add(1
)
33
my_list.add(2
)
34
my_list.add(3
)
35
my_list.add(4
)
36
my_list.add(5
)
37
38
39
for
num
in
my_list:
40
print
(num)
1.6?for...in...循環的本質
-
節省內存
-
惰性機制
-
不能反復,只能向下
1.7 迭代器的應用場景
斐波那契數列
1
class
FibIterator(object):
2
"""
3
斐波那契數列
4
"""
5
6
def
__init__
(self, n):
7
"""
8
:param n:int, 指明生成數列的前n個數
9
"""
10
self.n =
n
11
#
current用來保存當前生成到數列中的第幾個數了
12
self.current =
0
13
#
num1用來保存前前一個數,初始值為數列中的第一個數0
14
self.num1 =
0
15
#
num2用來保存前一個數,初始值為數列中的第二個數1
16
self.num2 = 1
17
18
def
__next__
(self):
19
"""
20
被next()函數調用來獲取下一個數
21
:return:
22
"""
23
24
if
self.current <
self.n:
25
num =
self.num1
26
self.num1, self.num2 = self.num2, self.num1+
self.num2
27
self.current += 1
28
return
num
29
else
:
30
raise
StopIteration
31
32
def
__iter__
(self):
33
"""
34
"迭代器的__iter__返回自身即可
35
:return:
36
"""
37
return
self
38
39
40
if
__name__
==
'
__main__
'
:
41
fib = FibIterator(10
)
42
for
num
in
fib:
43
print
(num, end=
"
"
)
除了for循環能接收可迭代對象,list、tuple等也能接收。
1
除了for循環能接收可迭代對象,list、tuple等也能接收。
2
3
li = list(FibIterator(15
))
4
print
(li)
5
tp = tuple(FibIterator(6
))
6
print
(tp)
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

