Python的迭代

来源:互联网 发布:时标网络的绘制步骤 编辑:程序博客网 时间:2024/06/10 02:35

python的迭代特别好用

  1. 何为迭代。顾名思义,迭代是重复有规律的做同一件事。英文是Iteration在代码中一般表现为循环,当我们要循环遍历一个List或Tuple时,就要用到迭代,类似于输出数组元素。
  2. 和C的对比。C语言循环输出,没有python简单
    for (i=0; i<list.length; i++) {    n = list[i];}
  3. python的迭代。非常灵活,语法for...in...,只要是对象可以迭代,那么for循环就可以正常运行,那么如何判断一个对象可否迭代?python可以导入collection模块的Iterable来实现判断:
    from collections import Iterable<pre name="code" class="html">isinstance('abc',Iterable)
    >>True
    isinstance(123,Iterable)
    >>False
  4. 单变量迭代输出。<pre name="code" class="python">for ch in 'abc':<span style="white-space:pre"></span>print(ch) 
  5. dict迭代。<pre name="code" class="html">d = {'a': 1, 'b': 2, 'c': 3}for key in d:<span style="white-space:pre"></span>print(key)<pre name="code" class="html">>>acb
    注意,因为dict不是按照list顺序迭代的,所以输出结果不一样
  6. 有下标的输出。python内置函数enumerate(),将list变成索引-元素对<pre name="code" class="html">for i, value in enumerate(['A', 'B', 'C']):<span style="white-space:pre"></span>print(i, value)0 A1 B2 C
0 0