Python的迭代[dié dài]

    1. # 1、for 循环迭代字符串
    2. for char in 'liangdianshui' :
    3. print ( char , end = ' ' )
    4. print('\n')
    1. # 2、for 循环迭代 list
    2. list1 = [1,2,3,4,5]
    3. for num1 in list1 :
    4. print ( num1 , end = ' ' )
    5. print('\n')
    1. # 3、for 循环也可以迭代 dict (字典)
    2. dict1 = {'name':'两点水','age':'23','sex':'男'}
    3. for key in dict1 : # 迭代 dict 中的 key
    4. print ( key , end = ' ' )
    5. print('\n')
    6. for value in dict1.values() : # 迭代 dict 中的 value
    7. print ( value , end = ' ' )
    8. print ('\n')

    迭代器有两个基本的方法:iter()next(),且字符串,列表或元组对象都可用于创建迭代器,迭代器对象可以使用常规 for 语句进行遍历,也可以使用 next() 函数来遍历

    1. # 1、字符创创建迭代器对象
    2. str1 = 'liangdianshui'
    3. iter1 = iter ( str1 )
    4. # 2、list对象创建迭代器
    5. list1 = [1,2,3,4]
    6. iter2 = iter ( list1 )
    7. # 3、tuple(元祖) 对象创建迭代器
    8. tuple1 = ( 1,2,3,4 )
    9. iter3 = iter ( tuple1 )
    10. # for 循环遍历迭代器对象
    11. for x in iter1 :
    12. print ( x , end = ' ' )
    13. print('\n------------------------')
    14. # next() 函数遍历迭代器
    15. while True :
    16. try :
    17. print ( next ( iter3 ) )
    18. except StopIteration :
    19. break