龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > python编程 >

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

时间:2014-10-03 02:29来源:网络整理 作者:网络 点击:
分享到:
跟一些比较牛X的程序员交流,经常听到他们嘴里冒出一个不标准的英文单词,而loop、iterate、traversal和recursion如果不在其内,总觉得他还不够牛X。当让,真正牛X的绝对不会这么说的,他

哦,这就是真正牛X的程序员。不过,他也仅仅是牛X罢了,还不是大神。大神程序员是什么样儿呢?他是扫地僧,大隐隐于市。

先搞清楚这些名词再说别的:

循环(loop),指的是在满足条件的情况下,重复执行同一段代码。比如,while语句。
迭代(iterate),指的是按照某种顺序逐个访问列表中的每一项。比如,for语句。
递归(recursion),指的是一个函数不断调用自身的行为。比如,以编程方式输出著名的斐波纳契数列。
遍历(traversal),指的是按照一定的规则访问树形结构中的每个节点,而且每个节点都只访问一次。
对于这四个听起来高深莫测的词汇,在教程中,已经涉及到了一个——循环(loop),本经主要介绍一下迭代(iterate),看官在网上google,就会发现,对于迭代和循环、递归之间的比较的文章不少,分别从不同角度将它们进行了对比。这里暂不比较,先搞明白python中的迭代。之后适当时机再比较,如果我不忘记的话,哈哈。

逐个访问

在python中,访问对象中每个元素,可以这么做:(例如一个list)

复制代码 代码如下:

>>> lst
['q', 'i', 'w', 's', 'i', 'r']
>>> for i in lst:
...     print i,
...
q i w s i r

除了这种方法,还可以这样:

复制代码 代码如下:

>>> lst_iter = iter(lst)    #对原来的list实施了一个iter()
>>> lst_iter.next()         #要不厌其烦地一个一个手动访问
'q'
>>> lst_iter.next()
'i'
>>> lst_iter.next()
'w'
>>> lst_iter.next()
's'
>>> lst_iter.next()
'i'
>>> lst_iter.next()
'r'
>>> lst_iter.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

做为一名优秀的程序员,最佳品质就是“懒惰”,当然不能这样一个一个地敲啦,于是就:

复制代码 代码如下:

>>> while True:
...     print lst_iter.next()
...
Traceback (most recent call last):      #居然报错,而且错误跟前面一样?什么原因
  File "<stdin>", line 2, in <module>
StopIteration

>>> lst_iter = iter(lst)                #那就再写一遍,上面的错误暂且搁置,回头在研究
>>> while True:
...     print lst_iter.next()
...
q                                       #果然自动化地读取了
i
w
s
i
r
Traceback (most recent call last):      #读取到最后一个之后,报错,停止循环
  File "<stdin>", line 2, in <module>
StopIteration
>>>

首先了解一下上面用到的那个内置函数:iter(),官方文档中有这样一段话描述之:

复制代码 代码如下:

iter(o[, sentinel])
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, o must be a collection object which supports the iteration protocol (the iter() method), or it must support the sequence protocol (the getitem() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

精彩图集

赞助商链接