zoukankan      html  css  js  c++  java
  • Python学习札记(十六) 高级特性2 迭代

    参考:迭代

    Note

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

    在C、C++、Java等语言中,for循环迭代是通过下标实现的,如:

    for (int i = 0; i < s.length(); i++) {
        printf("%c ", s[i]);
    }
    

    而在Python中,迭代是通过for...in...实现的,只要对象是可迭代对象,无论支持下标与否,都可以进行迭代。

    eg.

    #!/usr/bin/env python3
    
    L = ['it', 'is', 'a', 'list']
    
    for i in range(4) :
    	print(L[i])
    
    T = ('it', 'is', 'a', 'tuple')
    
    for i in range(4) :
    	print(T[i])
    

    output:

    sh-3.2# ./iteration1.py 
    it
    is
    a
    list
    it
    is
    a
    tuple
    

    因此,Pythonfor循环抽象程度要高于C、Java等语言的for循环。

    2.Python支持迭代不支持下标的对象,如dict与字符串:

    eg.dict

    dic = {'Chen' : 20, 'Number' : '952693358', 'City' : 'FuZhou'}
    
    for key in dic : 
    	print(key, dic[key])
    
    Chen 20
    Number 952693358
    City FuZhou
    

    eg.string

    str1 = 'HeyGirl'
    
    for i in str1 :
    	print(i)
    
    
    H
    e
    y
    G
    i
    r
    l
    

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

    3.判断一个对象是可迭代对象 => 通过collections模块的Iterable类型:

    >>> from collections import Iterable
    
    >>> isinstance('abc', Iterable) # 判断字符串
    True
    
    >>> isinstance(123, Iterable) # 判断整数
    False
    
    >>> isinstance((0,), Iterable) # 判断tuple
    True
    
    >>> isinstance(['a'], Iterable) # 判断list
    True
    
    >>> 
    

    4.如果要使list实现下标循环 => 内置的enumerate函数 => 将list转换为索引-元素对。

    L = ['Chen', 'Mac', 'IPhone', 'Github']
    
    for i, value in enumerate(L) :
    	print(i, value)
    
    0 Chen
    1 Mac
    2 IPhone
    3 Github
    

    2017/2/5

  • 相关阅读:
    软件测试人员的年终绩效考核怎么应对
    收藏
    顶踩组件 前后两版
    订阅组件
    hdu 1963 Investment 完全背包
    hdu 4939 Stupid Tower Defense 动态规划
    hdu 4405 Aeroplane chess 动态规划
    cf 414B Mashmokh and ACM 动态规划
    BUPT 202 Chocolate Machine 动态规划
    hdu 3853 LOOPS 动态规划
  • 原文地址:https://www.cnblogs.com/qq952693358/p/6368141.html
Copyright © 2011-2022 走看看