zoukankan      html  css  js  c++  java
  • Python进阶07 迭代

    如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration),也就是遍历。

    在Python中,迭代是通过for ... in来完成的。Python的for循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上。

    可迭代对象也就是可使用for循环遍历的对象。

    # list迭代
    list = [1, 2, 3, 4, 5, 6]
    
    for d in list:
        print(d)
    # dict迭代
    d = {'a': 1, 'b': 2, 'c': 3}
    for key in d:
        print(key)

    字符串也是可迭代对象,因此,也可以作用于for循环:

    # 字符串迭代
    for c in 'ABC':
        print(c)

    所以,当我们使用for循环时,只要作用于一个可迭代对象,for循环就可以正常运行,而我们不太关心该对象究竟是list还是其他数据类型。

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

    >>> from collections import Iterable
    >>> isinstance('ABC', Iterable) True >>> isinstance([1, 2, 3], Iterable) True >>> isinstance((1, 2, 3), Iterable) True >>> isinstance(123, Iterable) False

    参考文章:

    https://www.liaoxuefeng.com/wiki/1016959663602400/1017316949097888

  • 相关阅读:
    asp Excel导入数据库
    Excel导出函数
    asp精简checkbox全选代码
    一个操作读写已存在excel 文件的例子
    asp中实现网络打印功能
    asp操作excel 技术总结
    asp初学者常用的代码
    asp连接各种其他数据库 的方法
    asp得到地址栏里"?"以后的字串
    asp判断今天是星期几
  • 原文地址:https://www.cnblogs.com/mazhiyong/p/12564340.html
Copyright © 2011-2022 走看看