# 一、迭代

``````
# -*- coding: UTF-8 -*-

# 1、for 循环迭代字符串
for char in 'liangdianshui' :
print ( char , end = ' ' )

print('\n')

# 2、for 循环迭代 list
list1 = [1,2,3,4,5]
for num1 in list1 :
print ( num1 , end = ' ' )

print('\n')

# 3、for 循环也可以迭代 dict （字典）
dict1 = {'name':'两点水','age':'23','sex':'男'}

for key in dict1 :    # 迭代 dict 中的 key
print ( key , end = ' ' )

print('\n')

for value in dict1.values() :   # 迭代 dict 中的 value
print ( value , end = ' ' )

print ('\n')

# 如果 list 里面一个元素有两个变量，也是很容易迭代的
for x , y in [ (1,'a') , (2,'b') , (3,'c') ] :
print ( x , y )

``````

``````l i a n g d i a n s h u i

1 2 3 4 5

name age sex

1 a
2 b
3 c
``````

# 二、Python 迭代器

``````# 1、字符创创建迭代器对象
str1 = 'liangdianshui'
iter1 = iter ( str1 )

# 2、list对象创建迭代器
list1 = [1,2,3,4]
iter2 = iter ( list1 )

# 3、tuple(元祖) 对象创建迭代器
tuple1 = ( 1,2,3,4 )
iter3 = iter ( tuple1 )

# for 循环遍历迭代器对象
for x in iter1 :
print ( x , end = ' ' )

print('\n------------------------')

# next() 函数遍历迭代器
while True :
try :
print ( next ( iter3 ) )
except StopIteration :
break

``````

``````l i a n g d i a n s h u i
------------------------
1
2
3
4
``````

# 三、lsit 生成式（列表生成式）

## 1、创建 list 的方式

``````# -*- coding: UTF-8 -*-

list1=list ( range (1,31) )
print(list1)
``````

``````[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
``````

``````print('\n'.join([' '.join ('%dx%d=%2d' % (x,y,x*y)  for x in range(1,y+1)) for y in range(1,10)]))
``````

``````1x1= 1
1x2= 2 2x2= 4
1x3= 3 2x3= 6 3x3= 9
1x4= 4 2x4= 8 3x4=12 4x4=16
1x5= 5 2x5=10 3x5=15 4x5=20 5x5=25
1x6= 6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7= 7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8= 8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9= 9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
``````

## 2、list 生成式的创建

``````[expr for iter_var in iterable]
[expr for iter_var in iterable if cond_expr]
``````

``````# -*- coding: UTF-8 -*-
lsit1=[x * x for x in range(1, 11)]
print(lsit1)
``````

``````[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
``````

``````# -*- coding: UTF-8 -*-
lsit1= [x * x for x in range(1, 11) if x % 2 == 0]
print(lsit1)
``````

``````[4, 16, 36, 64, 100]
``````

``````# -*- coding: UTF-8 -*-
lsit1= [(x+1,y+1) for x in range(3) for y in range(5)]
print(lsit1)
``````

``````[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5)]
``````

# 四、生成器

## 2、生成器的创建

``````# -*- coding: UTF-8 -*-
gen= (x * x for x in range(10))
print(gen)
``````

``````<generator object <genexpr> at 0x0000000002734A40>
``````

## 3、遍历生成器的元素

``````# -*- coding: UTF-8 -*-
gen= (x * x for x in range(10))

for num  in  gen :
print(num)
``````

## 4、以函数的形式实现生成器

``````# -*- coding: UTF-8 -*-
def my_function():
for i in range(10):
print ( i )

my_function()
``````

``````0
1
2
3
4
5
6
7
8
9
``````

``````# -*- coding: UTF-8 -*-
def my_function():
for i in range(10):
yield i

print(my_function())
``````

``````<generator object my_function at 0x0000000002534A40>
``````

``````# -*- coding: UTF-8 -*-
def fibon(n):
a = b = 1
for i in range(n):
yield a
a, b = b, a + b

# 引用函数
for x in fibon(1000000):
print(x , end = ' ')
``````

``````# -*- coding: UTF-8 -*-
def odd():
print ( 'step 1' )
yield ( 1 )
print ( 'step 2' )
yield ( 3 )
print ( 'step 3' )
yield ( 5 )

o = odd()
print( next( o ) )
print( next( o ) )
print( next( o ) )
``````

``````step 1
1
step 2
3
step 3
5
``````

## 5、打印杨辉三角

``````# -*- coding: UTF-8 -*-
def triangles( n ):         # 杨辉三角形
L = [1]
while True:
yield L
L.append(0)
L = [ L [ i -1 ] + L [ i ] for i in range (len(L))]

n= 0
for t in triangles( 10 ):   # 直接修改函数名即可运行
print(t)
n = n + 1
if n == 10:
break
``````

``````[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
``````

# 五、迭代器和生成器综合例子

## 1、反向迭代

``````list1 = [1,2,3,4,5]
for num1 in list1 :
print ( num1 , end = ' ' )
``````

``````list1 = [1,2,3,4,5]
for num1 in reversed(list1) :
print ( num1 , end = ' ' )
``````

``````# -*- coding: UTF-8 -*-

class Countdown:
def __init__(self, start):
self.start = start

def __iter__(self):
# Forward iterator
n = self.start
while n > 0:
yield n
n -= 1

def __reversed__(self):
# Reverse iterator
n = 1
while n <= self.start:
yield n
n += 1

for rr in reversed(Countdown(30)):
print(rr)
for rr in Countdown(30):
print(rr)
``````

## 2、同时迭代多个序列

``````# -*- coding: UTF-8 -*-

names = ['laingdianshui', 'twowater', '两点水']
ages = [18, 19, 20]
for name, age in zip(names, ages):
print(name,age)
``````

``````laingdianshui 18
twowater 19

``````

``````# -*- coding: UTF-8 -*-

names = ['laingdianshui', 'twowater', '两点水']
ages = [18, 19, 20]

dict1= dict(zip(names,ages))

print(dict1)

``````

``````{'laingdianshui': 18, 'twowater': 19, '两点水': 20}
``````