GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing raw.githubusercontent.com — raw.githubusercontent.com >"But be on your guard so that your hearts are not wighted down with dissipation and drunkenness and the worries of this life, and that day close down upon you suddenly like a trap. For it will overtake all who live on the face of the whole earht. But staty alert at all times, praying that you may have strength to eacape all these things that must happen, and to stand before the Son of Man."
>你们要谨慎,恐怕因贪食醉酒并今生的思虑,累住你们的心,那日子就如同网罗忽然临到你们。因为那日子要这样临到全地上一切居住的人。你们要时时儆醒,常常祈求,是你们能逃避这一切要来的事,得以站立在人子面前。(LUKE 21:34-36)
#语句(3)
循环,你我都在其中。
日月更迭,斗转星移,无不是循环;王朝更迭,子子孙孙,从某个角度看也都是循环。
循环是现实生活中常见的现象。
编程语言就是要解决现实问题的,因此也少不了要循环。
##for循环
在高级编程语言中,大多数都有for循环(for loop),关于这种循环,我借用[维基百科中“for loop”](https://en.wikipedia.org/wiki/For_loop)的说明,帮助大家理解。
>In computer science a for-loop (or simply for loop) is a programming language control statement for specifying iteration, which allows code to be executed repeatedly. The syntax of a for-loop is based on the heritage of the language and the prior programming languages it borrowed from, so programming languages that are descendants of or offshoots of a language that originally provided an iterator will often use the same keyword to name an iterator, e.g., descendants of ALGOL use "for", while descendants of Fortran use "do." There are other possibilities, for example COBOL which uses "PERFORM VARYING".
如果看上面的英文有点难度,可以看下面的翻译,当然是很烂的翻译,绝对达不到“信雅达”的境界,虽然一直追求“德艺双馨”。
>在计算机科学中for循环是编程语言中针对可迭代对象的语句,它允许代码被重复执行。for循环的语法是在对历史上的编程语言继承和借鉴基础上形成的,该语言原来有迭代器,则后来的编程语言也用同样的关键词来实现迭代,比如ALGOL系的使用“for”,而Fortan系的使用“do”,也有例外,如COBOL用“PERFORM VARYING”。
for循环是从ALGOL那里继承过来的。ALGOL(ALGOrithmic Language)是最早的高级编程语言(几乎没有之一),后来的不少高级语言都继承了ALGOL的某些特性,比如Pascal、Ada、C语言等,也包括Python。
维基百科上对此有非常清晰的说明。
>The name for-loop comes from the English word for, which is used as the keyword in most programming languages to introduce a for-loop. The term in English dates to ALGOL 58 and was popularized in the influential later ALGOL 60; it is the direct translation of the earlier German für, used in Superplan (1949–1951) by Heinz Rutishauser, who also was involved in defining ALGOL 58 and ALGOL 60. The loop body is executed "for" the given values of the loop variable, though this is more explicit in the ALGOL version of the statement, in which a list of possible values and/or increments can be specified.
在ALGOL中,循环的关键词就是用for。所以,Python要继承这个光荣传统,也用for来实现循环。
于是有了:for语句。
其基本结构是:
for 循环规则:
操作语句
从这个基本结构看,有着同if条件语句类似的地方:都有冒号;语句块都要四个空格缩进。
##从例子中理解for循环
下面这个例子似曾相识。
>>> hello = "world"
>>> for i in hello:
... print i #Python 3: print(i)
...
w
o
r
l
d
这个例子中实现的就是for循环。下面庖丁解牛:
1. `hello = "world"`,赋值语句,实现变量`hello`和字符串`"world"`之间的引用关系。
2. `for i in hello:`,`for`是发起循环的关键词;`i in hello`是循环规则,字符串类型的对象是序列类型,能够从左到右一个一个地按照索引读出每个字符,于是变量`i`就按照索引顺序,从第一字符开始,依次获得该字符的引用。
3. 当 `i="w"`的时候,执行`print i`或者`print(i)`,打印出了字母w;然后循环第二次,让 `i="e"`,执行`print i`或者`print(i)`,打印出字母e;……,如此循环下去,一直到最后一个字符被打印出来,循环自动结束。注意,每次打印之后,要换行。如果不想换行,怎么办?参见[《语句(1)》](./121.md)中相关内容。
因为可以也通过使用索引,得到序列对象的某个元素。所以,还可以通过下面的循环方式实现同样效果:
>>> for i in range(len(hello)):
... print hello[i] #Python 3: print(hello[i])
...
w
o
r
l
d
其工作方式是:
1. `len(hello)`得到hello引用的字符串的长度,为5
2. `range(len(hello)`,就是`range(5)`,也就是`[0, 1, 2, 3, 4]`,对应这`"world"`每个字母索引。这里应用了一个新的函数`range()`,关于它的用法,继续阅读,就能看到了。
3. `for i in range(len(hello))`,就相当于`for i in [0,1,2,3,4]`,让`i`依次得到列表中的各个值。当`i=0`时,打印`hello[0]`,也就是第一个字符。然后顺序循环下去,直到最后一个`i=4`为止。
以上的循环举例中,显示了对字符串的字符依次获取,也涉及了列表,感觉不过瘾呀。
那好,看下面对列表的循环:
>>> ls_line = ['Hello', 'I am qiwsir', 'Welcome you', '']
>>> for word in ls_line:
... print word #Python 3: print(word)
...
Hello
I am qiwsir
Welcome you
>>> for i in range(len(ls_line)):
... print ls_line[i] #Python 3: print(ls_line[i])
...
Hello
I am qiwsir
Welcome you
以上两个例子中,是将for循环用于字符串和列表,此外,还可以用于字典、元组。例如:
>>> d = dict([("website", "www.itdiffer.com"), ("lang", "python"), ("author", "laoqi")])
>>> d
{'website': 'www.itdiffer.com', 'lang': 'python', 'author': 'laoqi'}
>>> for k in d:
print k #Python 3: print(k)
输出结果是:
website
lang
author
注意到,上面的循环,其实是读取了字典的key。在字典中,有一个方法,`dict.keys()`,得到的是字典key列表。
>>> for k in d.keys():
print k #Python 3: print(k)
website
lang
author
这种循环方法和上面的循环方法,结果是一样的,但是,这种方法并不提倡,以为它在执行速度上表现欠佳。
如果要获得字典的value怎么办?不要忘记`dict.values()`方法。读者可以自行测试一番。
除了可以单独获得key或者value的循环之外,还可以这么做:
>>> for k, v in d.items():
print k + "-->" + v #Python 3: print(k+"-->"+v)
website-->www.itdiffer.com
lang-->python
author-->laoqi
在工程实践中,你一定会遇到非常大的字典。用上面的方法,要把所有的内容都读入内存,内存东西多了,可能会出麻烦。为此,Python中提供了另外的方法。
>>> for k,v in d.iteritems(): #注意:仅在Python2中可用,Python 3中已经做了优化,d.item()即有同等功能。
print k + "-->" + v
website-->www.itdiffer.com
lang-->python
author-->laoqi
这里是循环一个迭代器,迭代器在循环中有很多优势。除了刚才的`dict.iteritems()`之外,还有`dict.itervalues()`,`dict.iterkeys()`供你选用(以上三个`dict.iter*`都只用在Python 2中,Python 3中已经不需要了)。
>>> d.iteritems() #注意:仅在Python2中可用。
|
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |