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,并且循环打印它们:
[python]
the_count = [1, 2, 3, 4, 5] 
fruits = ['apples', 'oranges', 'pears', 'apricots'] 
change = [1, 'pennies', 2, 'domes', 3, 'quarters'] 
 
 
# this first kind of for-loop goes through a list 
for number in the_count: 
    print "This is count %d" % number 
 
 
# same as above 
for fruit in fruits: 
    print "A fruit of type: %s" % fruit 
 
 
# also we can go through mixed lists too 
# notice we have to use %r since we don't know what's in it 
for i in change: 
    print "I got %r" % i 
 
 
# we can also build lists, first start with an empty on 
elements = [] 
 
 
# then use the range function to do 0 to 5 counts 
for i in range(0, 6): 
    print "Adding %d to the list." % i 
    # append is a function that lists understand 
    elements.append(i) 
 
 
# now we can print them out too 
for i in elements: 
    print "Elements was: %d" % i 


运行结果
root@he-desktop:~/mystuff# python ex32.py
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got 'pennies'
I got 2
I got 'domes'
I got 3
I 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: 0
Elements was: 1
Elements was: 2
Elements was: 3
Elements was: 4
Elements was: 5

加分练习
1. 弄懂range函数。
range([start], stop[, step])
产生一个整数列表,step默认是1,如果start没有赋值,默认是从0开始。

2. 你能不能不使用22行的for循环,而直接使用range给elemens赋值呢?
elements = range(0, 6)

3. 查看list的帮助文档,看看append附近还有什么函数。


作者:lixiang0522

相关内容

    暂无相关文章

评论关闭