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

    如果给定一个list或tuple,可以使用for循环来遍历,这种遍历称为迭代(Iteration)。python中的迭代是通过for...in 来完成,不仅可迭代list/tuple。还可迭代其他对象。


    # 迭代list
    >>> l = list(range(10))
    >>> for item in l:
    ... print(item)

    # 迭代dict,由于dict的存储不是像list那样顺序存储,所有迭代结果可能不是按顺序的
    >>> d = {'a':1, 'b':2}
    >>> for key in d: # 默认是迭代的key
    ... print(key)
    ...
    b
    a
    >>> for value in d.values(): # 迭代value
    ... print(value)
    ...
    2
    1
    >>> for k,v in d.items(): # 迭代key和value
    ... print(k, v)
    ...
    b 2
    a 1

    # 迭代字符串
    >>> for ch in 'abc':
    ... print(ch)
    ...
    a
    b
    c

    当使用for时,只要作用与一个迭代对象,就可以正常运行,我们不需要关注迭代对象是list还是其他数据类型。可以通过collections模块的Iterable类型判断一个对象是否是可迭代对象:

    >>> from collections import Iterable
    >>> isinstance('abc', Iterable) # str类型可迭代
    True
    >>> isinstance(123, Iterable) # 整数不可迭代
    False
    >>> dict={'a':1}
    >>> isinstance(dict, Iterable) # dict类型可迭代
    True


    python内置的enumerate函数可以将list变成索引-元素对。这样可以在for中迭代索引和对象本身:

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

  • 相关阅读:
    docker安装dvwa
    新版recon-ng安装模块
    docker多段构建nessus镜像
    docker安装Nessus
    docker快速安装openvas
    pyinstaller打包一些三方库后,报资源不存在
    python解决“failed to execute pyi_rth_pkgres”问题
    Proxmox6.2简单配置
    JavaScript全面学习(koa2.0)/MVC实现登录
    windows下react-native环境配置的那些坑
  • 原文地址:https://www.cnblogs.com/WebLinuxStudy/p/12713596.html
Copyright © 2011-2022 走看看