跟老齐学Python之让人欢喜让人忧的迭代

2019-10-05 16:50:37丽君

再有,我们用for来实现迭代,在本质上,就是自动调用next(),只不过这个工作,已经让for偷偷地替我们干了,到这里,列位是不是应该给for取另外一个名字:它叫雷锋。

前面提到了,列表解析也能够做为迭代工具,在研究列表的时候,看官想必已经清楚了。那么对文件,是否可以用?试一试:


>>> [ line for line in open('208.txt') ]
['Learn python with qiwsir.n', 'There is free python course.n', 'The website is:n', 'http://qiwsir.github.ion', 'Its language is Chinese.n']

至此,看官难道还不为列表解析所折服吗?真的很强大,又强又大呀。

其实,迭代器远远不止上述这么简单,下面我们随便列举一些,在python中还可以这样得到迭代对象中的元素。


>>> list(open('208.txt'))
['Learn python with qiwsir.n', 'There is free python course.n', 'The website is:n', 'http://qiwsir.github.ion', 'Its language is Chinese.n']

>>> tuple(open('208.txt'))
('Learn python with qiwsir.n', 'There is free python course.n', 'The website is:n', 'http://qiwsir.github.ion', 'Its language is Chinese.n')

>>> "$$$".join(open('208.txt'))
'Learn python with qiwsir.n$$$There is free python course.n$$$The website is:n$$$http://qiwsir.github.ion$$$Its language is Chinese.n'

>>> a,b,c,d,e = open("208.txt")
>>> a
'Learn python with qiwsir.n'
>>> b
'There is free python course.n'
>>> c
'The website is:n'
>>> d
'http://qiwsir.github.ion'
>>> e
'Its language is Chinese.n'

上述方式,在编程实践中不一定用得上,只是向看官展示一下,并且看官要明白,可以这么做,不是非要这么做。

补充一下,字典也可以迭代,看官自己不妨摸索一下(其实前面已经用for迭代过了,这次请摸索一下用iter()...next()手动一步一步迭代)。