zoukankan      html  css  js  c++  java
  • python-迭代

    其实我理解的,迭代就是循环,与其它语言中的循环一样。像java中取数组元素,需循环读取,语法通过下标读取

    for(int i;i<list.length();i++){
      System.out.println(list[i])  
    }
    

    python中的list和tuple都是可以利用迭代循环读取元素的

    1、list的循环读取

    >>> L=['a','b','c','d',10]
    >>> for x in L:
    	print(x)
    	
    a
    b
    c
    d
    10
    

    2、tuple的循环读取

    >>> R=(1,2,3,'a','b','c')
    >>> for i in R:
    	print(i)
    
    	
    1
    2
    3
    a
    b
    c
    

    3、字符串循环读取:其实把字符串看成一个list或tuple

    >>> E='abcdefg'
    >>> for i in E:
    	print(i)
    
    	
    a
    b
    c
    d
    e
    f
    g
    

    4、dict循环

    循环出key

    >>> N={'a':1,'b':'ttt','c':300}
    >>> for k in N:
    	print(k)
    
    	
    a
    b
    c
    

    另外几个例子:特别注意循环key,value的时候,语法问题

    >>> N={'a':1,'b':'ttt','c':300}
    >>> for k in N:
    	print(k)
    
    	
    a
    b
    c
    >>> for value in N.values():
    	print(value)
    
    	
    1
    ttt
    300
    >>> for k,v in N.items():
    	print(k)
    	print(v)
    
    	
    a
    1
    b
    ttt
    c
    300
    >>> for k,v in N.items():
    	print(k + ':' + v)
    	print(v)
    
    	
    Traceback (most recent call last):
      File "<pyshell#276>", line 2, in <module>
        print(k + ':' + v)
    TypeError: must be str, not int
    >>> for k,v in N.items():
    	print(k  ':'  v)
    	
    SyntaxError: invalid syntax
    >>> for k,v in N.items():
    	print(k  ,':' , v)
    
    	
    a : 1
    b : ttt
    c : 300
    >>> 
    

    5、以上几种类型的数据,都可用for循环出来,for循环只要作用于一个可迭代的对象就可以正常运行,而我们不太关心该对象是list?tuple?dict?或其它

    那么,我们要如何判断一个对象是可迭代的对像呢,方法是通过collections模块的Iterable类型判断:

    >>> from collections import Iterable
    >>> isinstance('abc',Iterable)
    True
    >>> isinstance(['1','ccc',200],Iterable)
    True
    >>> isinstance(123,Iterable)
    False
    >>> isinstance((123),Iterable)
    False
    >>> isinstance(('a','b','c'),Iterable)
    True
    >>> isinstance({'a':1,'b':2,'c':'xxx'},Iterable)
    True
    

    6、小技能扩展

    如果要对list实现类似javav那样的下标循环怎么办?

    python自带的enumerate(枚举),与java中的enum一样。可以把list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身

    >>> for i,value in enumerate(['a','b','c']):
    	print(i,value)
    
    	
    0 a
    1 b
    2 c
    

    再来个实例结束今天的课程 :

    >>> for x,y in [(1,2),(3,4),(5,6)]:
    	print(x,y)
    
    	
    1 2
    3 4
    5 6
    

      

  • 相关阅读:
    wireshark安装
    高效使用搜索引擎
    MFC 网络编程 -- 总结
    MFC Grid control 2.27
    A Popup Progress Window
    Showing progress bar in a status bar pane
    Progress Control with Text
    Report List Controls
    第三方
    CBarChart柱形图类
  • 原文地址:https://www.cnblogs.com/sincoolvip/p/7280667.html
Copyright © 2011-2022 走看看