Ex32 for-loop

for 循环和 List 类型

循环语句在之前也涉及到,While循环。for循环,更适合做一些有确定循环数量的动作。while循环终止条件相对模糊。for常常于list类型联合使用。 list类型,类似于 C 语言中的数组概念,动态数组。list类型最大的好处,可以对内部元素进行读写操作,就像文件一样。这点十分给力,很多操作,都是动态调整的,实现难以确定具体内容,或元素类型或元素数量。碰到这种情况,list绝对是瑞士军刀一般的武器。

示例代码

Ex32 for循环示例代码,如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
the_count = [1,2,3,4,5]
fruits = ['apple', 'oranges', 'pears', 'apricots']
change = [1, 'pennies',2,'dimes',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 list, first strt with an empty one
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 "Element was : %d" % i

示例运行,结果如下图:

小结

  1. for循环的循环变量(i,count…)不必单独定义,直接在语句中使用;
  2. list数据类型,可以容纳多种类型数据混合,但是每个元素在都有自己的位置。另外,list类型,可以嵌套,实现多维数据
Licensed under CC BY-NC-SA 4.0
使用 Hugo 构建
主题 StackJimmy 设计