angrykola

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python的语法:

  • while与for
  • break与continue
  • range方法与切片
  • zip方法并行遍历
  • enumerate产生偏移和元素

while与for循环

#while循环是一条通用的循环语句,主要用于计数器
>>> a = []
>>> x = 0
>>> while x < 10:
    print('x = ',x,'a is ',a)
    a.append(x);x += 1

x =  0 a is  []
x =  1 a is  [0]
......
x =  9 a is  [0, 1, 2, 3, 4, 5, 6, 7, 8]

#for循环则通常设计用来遍历程序中各个项(序列需要真正可迭代的)
>>> for i in a:
    print('i is ',i)
    
i is  0
i is  1
......
i is  9

break与continue :

#break立即退出循环(忽略if、while旗下的整个语句)
#用while举例
>>> flag = True
>>> x
10
>>> while flag:
    if x == 5:
        break
    print('x =',x)
    x -= 1
    
x = 10
x = 9
......
x = 6

#continue跳回循环顶部,进行新一轮循环
#用for循环举例
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in a:
    print(i)
    if i >5:
        continue
    print('continue',i)
    i += 1

    
0
continue 0
1
......
continue 5
6
7
8
9

range函数与分片:

#通过range函数创建列表
>>> for i in range(10):
    a.append(i)    
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#部分遍历列表 range(start,stop,step)
>>> for i in range(0,len(a),2):print('a[%d] =%d '%(i,a[i]))
a[0] =0 
a[2] =2 
a[4] =4 
a[6] =6 
a[8] =8 

 zip函数并行遍历

#zip并行遍历
>>> L1= [1,2,3,4,5]
>>> L2= [6,7,8,9,0]
#通过zip创建列表
>>> list(zip(L1,L2))
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 0)]
#通过zip创建字典
>>> keys=['one','two','three']
>>> vals=['first','second','third']
>>> dic=dict(zip(keys,vals))
>>> dic
{'two': 'second', 'one': 'first', 'three': 'third'}
#同时在python3.0中,zip也是一个可迭代对象
#通过for循环进行迭代
>>> for x,y in zip(L1,L2):print(x,y)
1 6
2 7
......
5 0

enumerate产生偏移和元素

#enumerate方法简介
>>> word='The Bigbang'
>>> exa=enumerate(word)
#enmuerate函数会返回一个生成器对象,可用于迭代
>>> next(exa)
(0, 'T')
>>> next(exa)
(1, 'h')
......
>>> [x*y for (x,y) in enumerate(word)]
['', 'h', 'ee', '   ', 'BBBB', 'iiiii', 'gggggg', 'bbbbbbb', 'aaaaaaaa', 'nnnnnnnnn', 'gggggggggg']

 

 

posted on 2013-11-03 23:04  kolaman  阅读(189)  评论(0)    收藏  举报