• python笔记九(迭代)


    一、迭代

      通过for循环来遍历一个列表,我们称这种遍历的方式为迭代。只要是可迭代对象都可以进行迭代操作。

      以下代码可以用来判断一个对象是否是可迭代的。

      一类是集合数据类型,如listtupledictsetstr等;

      一类是generator,包括生成器和带yield的generator function(我们将在下一节中介绍)

    >>> from collections import Iterable
    >>> isinstance("abc",Iterable)
    True
    >>> isinstance([1,2,3],Iterable)
    True
    >>> isinstance({"name":"nadech"},Iterable)
    True

      通过迭代的方式,循环输出列表中的内容。

    names = ["nadech","aguilera","sara"]
    for name in names:
        print(name)

      如果在输出以上name的时候,我们希望在前边加上序号,变成索引-元素对的形式,那么可以通过enumerate函数实现。

    names = ["nadech","aguilera","sara"]
    for i,name in enumerate(names):
        print(i,name)

    #输出结果

     0 nadech
     1 aguilera
     2 sara

      在字典迭代的时候,我们可以迭代字典的key,value,或者是key-value对

    >>> d = {"name":"nadech","age":"22","address":"NANJING"}
    >>> for key in d:  #迭代key值
    ...     print(key)
    ...
    address
    name
    age
    >>> for value in d.values():   #迭代value值
    ...     print(value)
    ...
    NANJING
    nadech
    22
    >>> for key,value in d.items(): #迭代key-value对
    ...     print(key,value)
    ...
    address NANJING
    name nadech
    age 22

      类似的,在for循环中有两个变量,如:

    >>> for x, y in [(1, 1), (2, 4), (3, 9)]:
    ...     print(x,y)
    ...
    1 1
    2 4
    3 9
  • 相关阅读:
    VS2013搭建wxWidgets开发环境
    LinuxSystemProgramming-Syllabus
    Python入门2(Python与C语言语法的不同、Notepad++运行Python代码)
    Python入门1(简介、安装)
    面试题收集---grep和find的区别
    浅拷贝 和深拷贝
    使用 system.io.filesysteminfo 来查找文件。
    使用FileSystemWatcher捕获系统文件状态
    system.io.file创建
    Javascript诞生记 [转载]
  • 原文地址:https://www.cnblogs.com/nadech/p/8033815.html
Copyright © 2020-2023  润新知