这里主要说的是用python中的range来模拟for循环
转载请声明本文的引用出处:仰望大牛的小清新
1.range(var1,var2,var3): range产生一个列表(list),var1<=其中元素<var2,即左闭右开的区间,每个元素之间的间隔为var3,如果没有给var3,默认为1,并且var3 可以为负数,当var3所确定的方向和var1,var2之间的方向不一致时,返回空列表,具体请看下面的例子
2.list:list是有序组织的容纳元素的容器,用[(left bracket and right bracket)]括起来,list本身可嵌套,意味着list中的元素可以是另一个list。注意,python中list的下标从0开始。
一个简单的练习代码如下:
1 # -*- coding: utf-8 -*- 2 from __future__ import unicode_literals 3 print "练习 list 以及 用range实现的 for 循环" 4 5 the_count = [1, 2, 3, 4, 5] 6 fruits = ['apples', 'oranges', 'pears', 'apricots'] 7 change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] 8 9 # this first kind of for-loop goes through a list 10 11 for number in the_count: 12 print "This is count %d" % number 13 14 # same as above 15 for fruit in fruits: 16 print "A fruit of type: %s" % fruit 17 18 # also we can go through mixed lists too 19 # notice we have to use %r since we don't know what's in it 20 for i in change: 21 print "I got %r" % i 22 23 # we can also build lists, first start with an empty one 24 elements = [] # empty list 25 26 # then use the range function to do 0 to 5 counts 27 for i in range(0, 6): 28 print "Adding %d to the list." % i 29 # append is a function that lists understand 30 elements.append(i) 31 32 # now we can print them out too 33 for i in elements: 34 print "Elements was: %d" % i