Learn Python The Hard Way学习(32) - 循环和列表
下面我们会做一些有趣的事情,如果跟着进度学习的话,你会发现你已经可以用if语句和布尔表达式做很多事情了。
不管怎样,程序会做一些重复的事情,下面我们就用for循环打印一个列表变量。做这个练习的时候你必须自己弄懂它们的含义和作用。
在使用for循环之前,我们需要一个东西保存循环的值,最好的方法是使用一个列表,列表就是按照顺序保存数据的容器,不是很复杂,就是一种新的语法而已,结构像下面这样:hairs = ['brown', 'blond', 'red']eyes = ['brown', 'blue', 'green']weights = [1, 2, 3, 4]
list以 [ 号开头,里面的元素以 , 号分隔,像函数的参数一样,然后以 ] 结束,python把所有这些包含在一个变量中。
敬告:上一个练习中我们用if语句包含if语句,很多人不明白为什么一个东西可以包含另外一个东西,在程序中这是很常见的,你会发现函数可以包含函数,list可以包含list。如果你发现一种不理解的结构,用笔记录下来,以后弄明白它。
下面我们来看一些list,并且循环打印它们:
运行结果root@he-desktop:~/mystuff# python ex32.py This is count 1This is count 2This is count 3This is count 4This is count 5A fruit of type: applesA fruit of type: orangesA fruit of type: pearsA fruit of type: apricotsI got 1I got 'pennies'I got 2I got 'domes'I got 3I got 'quarters'Adding 0 to the list.Adding 1 to the list.Adding 2 to the list.Adding 3 to the list.Adding 4 to the list.Adding 5 to the list.Elements was: 0Elements was: 1Elements was: 2Elements was: 3Elements was: 4Elements was: 5
加分练习1. 弄懂range函数。range([start], stop[, step])产生一个整数列表,step默认是1,如果start没有赋值,默认是从0开始。
2. 你能不能不使用22行的for循环,而直接使用range给elemens赋值呢?elements = range(0, 6)
3. 查看list的帮助文档,看看append附近还有什么函数。