• 遍历Python中的列表


     

    List等效于其他语言中的数组,其额外的好处是可以动态调整大小。在Python中,列表是数据结构中的一种容器,用于同时存储多个数据。与Sets不同,Python中的列表是有序的,并且具有确定的计数。

    有多种方法可以迭代Python中的列表。让我们看看在Python中迭代列表的所有不同方法,以及它们之间的性能比较。

    方法1:使用For循环

    # Python3 code to iterate over a list 
    list = [1, 3, 5, 7, 9] 
    
    # Using for loop 
    for i in list: 
        print(i) 
    输出:
    1个
    3
    5
    7
    9

     
    方法2: For循环和range()

    如果我们要使用从数字x到数字y迭代的传统for循环。

    # Python3 code to iterate over a list 
    list = [1, 3, 5, 7, 9] 
    
    # getting length of list 
    length = len(list) 
    
    # Iterating the index 
    # same as 'for i in range(len(list))' 
    for i in range(length): 
        print(list[i]) 
    输出:
    1个
    3
    5
    7
    9

    如果我们可以对元素进行迭代,则不建议对索引进行迭代(如方法1中所述)。
     
    方法3:使用while循环

    # Python3 code to iterate over a list 
    list = [1, 3, 5, 7, 9] 
    
    # Getting length of list 
    length = len(list) 
    i = 0
    
    # Iterating using while loop 
    while i < length: 
        print(list[i]) 
        i += 1
    输出:
    1个
    3
    5
    7
    9

     
    方法4:使用列表理解(可能是最具体的方法)。

    # Python3 code to iterate over a list 
    list = [1, 3, 5, 7, 9] 
    
    # Using list comprehension 
    [print(i) for i in list] 
    输出:
    1个
    3
    5
    7
    9

     
    方法5:使用enumerate()

    如果我们想将列表转换为可迭代的元组列表(或基于条件检查获得索引,例如在线性搜索中,可能需要保存最小元素的索引),则可以使用enumerate()函数。

    # Python3 code to iterate over a list 
    list = [1, 3, 5, 7, 9] 
    
    # Using enumerate() 
    for i, val in enumerate(list): 
        print (i, ",",val) 
    输出:
    0,1
    1、3
    2、5
    3、7
    4、9

    注意:甚至方法2都可以用来查找索引,但是方法1不能(除非每次迭代都增加一个额外的变量),方法5给出了这种索引的简明表示。
     
    方法#6:使用numpy

    对于非常大的n维列表(例如图像数组),有时最好使用外部库(例如numpy)。

    # Python program for 
    # iterating over array 
    import numpy as geek 
    
    # creating an array using 
    # arrange method 
    a = geek.arange(9) 
    
    # shape array with 3 rows 
    # and 4 columns 
    a = a.reshape(3, 3) 
    
    # iterating an array 
    for x in geek.nditer(a): 
        print(x) 
    输出:
    0
    1个
    2
    3
    4
    5
    6
    7
    8

    我们可以np.ndenumerate()用来模仿枚举的行为。numpy的强大功能来自于我们甚至可以控制访问元素的方式(Fortran顺序而不是C顺序,例如:)),但一个警告是np.nditer默认情况下将数组视为只读,因此一个人必须传递额外的标志,例如op_flags=[‘readwrite’]它才能修改元素

  • 相关阅读:
    P3932 浮游大陆的68号岛
    P4595 [COCI2011-2012#5] POPLOCAVANJE
    CF455E Function
    【转载】乱堆的东西
    BZOJ1034 [ZJOI2008]泡泡堂BNB[贪心]
    CSP2019退役记
    BZOJ5206 [Jsoi2017]原力[根号分治]
    luogu3651 展翅翱翔之时 (はばたきのとき)[基环树+贪心]
    BZOJ1040 [ZJOI2008]骑士[基环树DP]
    BZOJ3037 创世纪[基环树DP]
  • 原文地址:https://www.cnblogs.com/a00ium/p/13874747.html
Copyright © 2020-2023  润新知