cities = ['Shanghai','beijing','Chengdu'] i = 0 for c in cities: print(i +1,'-->',c) i += 1
更好的方法(使用 enumerate)
1 2 3
cities = ['Shanghai','beijing','Chengdu'] for i,city inenumerate(cities): print(i+1,'-->',city)
两个系列循环
对两个序列进行计算或处理
一般方法
1 2 3 4 5
names = ['leo','jack','james'] colors = ['red','green','blue','yellow'] n = min(len(names),len(colors)) for i inrange(n): print(names[i],'-->',colors[i])
更好的方法(使用 zip)
1 2 3 4
names = ['leo','jack','james'] colors = ['red','green','blue','yellow'] for name,color inzip(names,colors): print(name,'-->',color)
交换变量
多个变量之间的交换,如冒泡排序法
一般方法
1 2 3 4 5 6 7
x = 1 y = 2 print('>>Before:x={},y={}'.format(x,y)) tmp = y y = x x = tmp print('>>After:x = {},y = {}'.format(x,y))