习题 32: 循环和列表
目标与感悟:
• for-loop的使用,首先定义一个列表,list = [1, 2, 'dda'],之后定义变量位于列表,再进行打印等操作。
例:
list =[1,2,'dda']
for a inlist:
print"I got %r "%a
• x.append(y)这个命令的作用是把y这个值所表达的内容添加到x的列表中。
假设先设置x列表=【】(空集)
那在运行x.append(y)命令之后x列表就会变成【y】
再次运行x.append(z)命令之后x列表就会变成【y,z】
• for-loop可以直接使用range函数,python中range()函数会从第一个开始,但不包含最后一个数字,range也是一个列表。
ex32.py
#-*- coding:utf-8-*-
#此章的主题是for循环
#[(左方括号)开头“打开”列表,然后写下你要放入列表的东西,用逗号隔开,就跟函数的参数一样,最后需要用 ] (右方括号)结束右方括号的定义。
#此处就是定义一个列表,共定义了3个,按顺序将列表中数赋予给变量
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
# for循环可以遍历任何序列的项目,如一个列表或者一个字符串。此处就是历遍the_count列表
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
#%r能够打印python中原本的代码
for i in change:
print "I got %r " %i
# we can also build lists, first start with an empty one
# 伏笔,此处定义一个新列表,列表为空
elements = []
# then use the range function to do 0 to 5 counts
# 此处可知python中range()函数会从第一个开始,但不包含最后一个数字
for i in range(0,6):
print "Adding %d to the list." % i
# append is a function that lists understand
elements.append(i)
#x.append(y),作用是把y这个值所表达的内容添加到x的列表中。
# now we can print them out too
# 此时对elements列表的值进行验证
for i in elements:
print "Element was: %d" % i
运行结果: