1.幾個(gè)名詞
- 循環(huán)(loop),指的是在滿足條件的情況下,重復(fù)執(zhí)行同一段代碼。比如,while語句。
- 迭代(iterate),指的是按照某種順序逐個(gè)訪問列表中的每一項(xiàng)。比如,for語句。
- 遞歸(recursion),指的是一個(gè)函數(shù)不斷調(diào)用自身的行為。比如,以編程方式輸出著名的斐波納契數(shù)列。
- 遍歷(traversal),指的是按照一定的規(guī)則訪問樹形結(jié)構(gòu)中的每個(gè)節(jié)點(diǎn),而且每個(gè)節(jié)點(diǎn)都只訪問一次。
2.迭代的基本操作,除了for,還可以使用iter()
>>> list1=['q','i','w','s','i','r']
# 使用iter()創(chuàng)建一個(gè)迭代器
>>> list2=iter(list1)
# 使用.__next__()一直迭代下去
>>> list2.__next__()
'q'
>>> list2.__next__()
'i'
>>> list2.__next__()
'w'
>>> list2.__next__()
's'
>>> list2.__next__()
'i'
>>> list2.__next__()
'r'
# 迭代到最后會(huì)報(bào)錯(cuò)...因?yàn)槟┪擦?# 使用for不會(huì)報(bào)錯(cuò)
>>> list2.__next__()
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
list2.__next__()
StopIteration
# 懶惰一點(diǎn)的辦法
# 需要重新賦值,因?yàn)橐呀?jīng)迭代到末尾了
# 這也是迭代器的特點(diǎn),要小心指針的位置
>>> list3=iter(list1)
>>> while True:
print(list3.__next__())
q
i
w
s
i
r
Traceback (most recent call last):
File "<pyshell#13>", line 2, in <module>
print(list3.__next__())
StopIteration
- 文件的迭代:之前的操作,使用readline()或者for()去遍歷,這里使用next(),for的本質(zhì)就是next():
>>> file=open('test3.txt')
# 文件對(duì)象不需要?jiǎng)?chuàng)建iter(),直接可以用
>>> file.__next__()
'Learn python with qiwsir.\n'
>>> file.__next__()
'There is free python course.\n'
>>> file.__next__()
'http://qiwsir.github.io\n'
>>> file.__next__()
'Its language is Chinese.'
>>> file.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
- 還可以使用list(),tuple(),''.join()獲取文件元素
>>> file=open('test3.txt')
>>> list(file)
['Learn python with qiwsir.\n', 'There is free python course.\n', 'http://qiwsir
.github.io\n', 'Its language is Chinese.']
# 需要重新賦值
>>> tuple(file)
()
>>> file=open('test3.txt')
>>> tuple(file)
('Learn python with qiwsir.\n', 'There is free python course.\n', 'http://qiwsir
.github.io\n', 'Its language is Chinese.')
>>> file=open('test3.txt')
>>> '$$$'.join(file)
'Learn python with qiwsir.\n$$$There is free python course.\n$$$http://qiwsir.gi
thub.io\n$$$Its language is Chinese.'
>>>
# 亮瞎眼的操作
>>> file=open('test3.txt')
# a,b,c,d,e=file 會(huì)報(bào)錯(cuò),file有四個(gè)元素,賦值5個(gè)報(bào)錯(cuò)
# 賦值的元素要?jiǎng)偤?
>>> a,b,c,d=file
>>> a
'Learn python with qiwsir.\n'
>>> b
'There is free python course.\n'
>>> c
'http://qiwsir.github.io\n'
>>> d
'Its language is Chinese.'